Last active
August 8, 2018 06:40
-
-
Save ericelliott/6da133a93d5b15676aa79ae2e23d814c to your computer and use it in GitHub Desktop.
Full demonstration of synchronous style flow control with generators.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const isPromise = obj => Boolean(obj) && typeof obj.then === 'function'; | |
const next = (iter, callback, prev = undefined) => { | |
const item = iter.next(prev); | |
const value = item.value; | |
if (item.done) return callback(prev); | |
if (isPromise(value)) { | |
value.then(val => { | |
setImmediate(() => next(iter, callback, val)); | |
}); | |
} else { | |
setImmediate(() => next(iter, callback, value)); | |
} | |
}; | |
const gensync = (fn) => | |
(...args) => new Promise(resolve => { | |
next(fn(...args), val => resolve(val)); | |
}); | |
/* How to use gensync() */ | |
const fetchSomething = () => new Promise((resolve) => { | |
setTimeout(() => resolve('future value'), 500); | |
}); | |
const asyncFunc = gensync(function* () { | |
const result = yield fetchSomething(); // returns promise | |
// waits for promise and uses promise result | |
yield result + ' 2'; | |
}); | |
// Call the async function and pass params. | |
asyncFunc('param1', 'param2', 'param3') | |
.then(val => console.log(val)); // 'future value 2' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment