Last active
April 12, 2018 09:08
-
-
Save kra3/f1acb5a5584d57ad3f6c94c37f04ac56 to your computer and use it in GitHub Desktop.
How Async Await behaves in loops
This file contains 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
// our cool promise of future; serialize promises | |
function future(val){ | |
console.log("lala ", val); | |
return new Promise((resolve, reject) => { | |
setTimeout(resolve, 2000, val); | |
}) | |
} | |
//1. await waits in this case | |
(async () => { | |
for (i in [1,2,3,4]) { | |
const x = await future(i); | |
console.log(x) | |
} | |
console.log('done') | |
})() | |
/* | |
lala 0 | |
Promise {<pending>} | |
0 | |
lala 1 | |
1 | |
lala 2 | |
2 | |
lala 3 | |
3 | |
done | |
*/ | |
//2. await won't wait in this case; fire and forget | |
(() => { | |
[1,2,3,4].forEach(async i => { | |
let x = await future(i); | |
console.log('-> ', x) | |
}); | |
console.log("done") | |
})() | |
/* | |
lala 1 | |
lala 2 | |
lala 3 | |
lala 4 | |
done | |
undefined | |
-> 1 | |
-> 2 | |
-> 3 | |
-> 4 | |
*/ | |
// 3.make use of inherent parallelism | |
(() => { | |
Promise.all([1,2,3,4].map(i => future(i))) | |
.then(result => result.forEach(x => console.log('-> ', x))); | |
console.log("done") | |
})() | |
/* | |
lala 1 | |
lala 2 | |
lala 3 | |
lala 4 | |
done | |
undefined | |
-> 1 | |
-> 2 | |
-> 3 | |
-> 4 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment