Skip to content

Instantly share code, notes, and snippets.

@pombadev
Created February 7, 2018 04:37
Show Gist options
  • Save pombadev/53c0179387d174e6ed1a150372fe9a4b to your computer and use it in GitHub Desktop.
Save pombadev/53c0179387d174e6ed1a150372fe9a4b to your computer and use it in GitHub Desktop.
Working with promises
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