Last active
September 19, 2017 16:23
-
-
Save dimpiax/ef207b3eabaebf2540d1f9183f0374ed to your computer and use it in GitHub Desktop.
Lite Promise.sync using async/await
This file contains 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 next = async (it, callback) => { | |
const { value, done } = it.next() | |
if (done) return [] | |
const result = await callback(value) | |
const nextResult = await next(it, callback) | |
return [result, ...nextResult] | |
} | |
const sync = async (value, callback) => { | |
const it = value[Symbol.iterator]() | |
const res = await next(it, callback) | |
return res | |
} | |
export default { | |
sync | |
} | |
// Usage: | |
/** | |
const result = await sync([1000, 500], async (value) => { | |
const res = await new Promise((res) => { setTimeout(res, value, value * 2) }) | |
return res | |
}) | |
console.log(result) // [2000, 1000] after 1500 ms | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment