Last active
May 10, 2018 11:21
-
-
Save Codesleuth/c2757fff487bc8223f53ee411ef2e14b to your computer and use it in GitHub Desktop.
Promise execution
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
async function main () { | |
const actions = [...Array(5)].map((_, i) => new Promise((resolve) => { | |
console.log(`Promise ${i} has started already...`) | |
console.time(`Promise ${i}`) | |
setTimeout(() => { | |
console.log(`Promise ${i} has finished!`) | |
console.timeEnd(`Promise ${i}`) | |
resolve() | |
}) | |
})) | |
// chain the promises | |
return Promise.all(actions) | |
} | |
main().then(() => console.log('After main')).catch(err => { | |
console.error(err) | |
process.exit(1) | |
}) | |
/* | |
$ node with-wait.js | |
Promise 0 has started already... | |
Promise 1 has started already... | |
Promise 2 has started already... | |
Promise 3 has started already... | |
Promise 4 has started already... | |
Promise 0 has finished! | |
Promise 0: 1.777ms | |
Promise 1 has finished! | |
Promise 1: 1.511ms | |
Promise 2 has finished! | |
Promise 2: 1.519ms | |
Promise 3 has finished! | |
Promise 3: 1.540ms | |
Promise 4 has finished! | |
Promise 4: 1.576ms | |
After main | |
*/ |
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
async function main () { | |
const actions = [...Array(5)].map((_, i) => new Promise((resolve) => { | |
console.log(`Promise ${i} has started already...`) | |
console.time(`Promise ${i}`) | |
setTimeout(() => { | |
console.log(`Promise ${i} has finished!`) | |
console.timeEnd(`Promise ${i}`) | |
resolve() | |
}) | |
})) | |
// note that none of the promises created above have a `.then` anywhere! | |
} | |
main().then(() => console.log('After main')).catch(err => { | |
console.error(err) | |
process.exit(1) | |
}) | |
/* | |
$ node without-wait.js | |
Promise 0 has started already... | |
Promise 1 has started already... | |
Promise 2 has started already... | |
Promise 3 has started already... | |
Promise 4 has started already... | |
After main | |
Promise 0 has finished! | |
Promise 0: 4.878ms | |
Promise 1 has finished! | |
Promise 1: 4.656ms | |
Promise 2 has finished! | |
Promise 2: 4.680ms | |
Promise 3 has finished! | |
Promise 3: 4.694ms | |
Promise 4 has finished! | |
Promise 4: 4.740ms | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment