Skip to content

Instantly share code, notes, and snippets.

@DadgadCafe
Created April 2, 2017 08:50
Show Gist options
  • Save DadgadCafe/5790e3fd2ac7583cc1e0503dbe312dd3 to your computer and use it in GitHub Desktop.
Save DadgadCafe/5790e3fd2ac7583cc1e0503dbe312dd3 to your computer and use it in GitHub Desktop.
chaining async flow, like in koa2.
// must return or await next() in koa2, otherwise promise chain will be terminated.
const delay = () => new Promise(resolve => {
console.log('delay...')
setTimeout(() => {
resolve()
}, 1000)
})
async function asyncf (n) {
if (n === 0) {
return 'done'
}
await delay()
return asyncf(n - 1)
}
function f (n) {
if (n === 0) {
return 'done'
}
// manually handle async
return delay()
.then(() => asyncf(n - 1))
}
Promise
// f(3) => p.then(/*..*/).then(/*..*/)
.resolve(f(3))
.then(v => {console.log(v)}) // after 3s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment