Created
February 7, 2018 04:37
-
-
Save pombadev/53c0179387d174e6ed1a150372fe9a4b to your computer and use it in GitHub Desktop.
Working with promises
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
const promises = [ | |
() => | |
new Promise(resolve => | |
setTimeout(() => { | |
resolve(console.log(1)); | |
}, Math.floor(Math.random() * 2000) + 1000) | |
), | |
() => | |
new Promise(resolve => | |
setTimeout(() => { | |
resolve(console.log(2)); | |
}, Math.floor(Math.random() * 2000) + 1000) | |
), | |
() => | |
new Promise(resolve => | |
setTimeout(() => { | |
resolve(console.log(3)); | |
}, Math.floor(Math.random() * 2000) + 1000) | |
), | |
() => | |
new Promise(resolve => | |
setTimeout(() => { | |
resolve(console.log(4)); | |
}, Math.floor(Math.random() * 2000) + 1000) | |
) | |
] | |
/* | |
Procress array in sequence. | |
Output: | |
1 | |
2 | |
3 | |
4 | |
Async/Await: **some time in ms** | |
*/ | |
(async () => { | |
console.time('Async/Await') | |
for (let item of promises) { | |
await item(); | |
} | |
console.timeEnd('Async/Await') | |
})(); | |
/* | |
Output: | |
? | |
? | |
? | |
? | |
Promise: **some time in ms** | |
*/ | |
(() => { | |
console.time('Promise') | |
Promise.all(promises.map(i => i())) | |
.then(() => { | |
console.timeEnd('Promise') | |
}) | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment