Skip to content

Instantly share code, notes, and snippets.

@dimpiax
Last active September 19, 2017 16:23
Show Gist options
  • Save dimpiax/ef207b3eabaebf2540d1f9183f0374ed to your computer and use it in GitHub Desktop.
Save dimpiax/ef207b3eabaebf2540d1f9183f0374ed to your computer and use it in GitHub Desktop.
Lite Promise.sync using async/await
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