Created
April 2, 2017 08:50
-
-
Save DadgadCafe/5790e3fd2ac7583cc1e0503dbe312dd3 to your computer and use it in GitHub Desktop.
chaining async flow, like in koa2.
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
// 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