Skip to content

Instantly share code, notes, and snippets.

@kra3
Last active Apr 12, 2018
Embed
What would you like to do?
How Async Await behaves in loops
// 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