Skip to content

Instantly share code, notes, and snippets.

@riltsken
Last active September 27, 2017 17:08
Show Gist options
  • Save riltsken/8043caec93f4219d64e578b694982917 to your computer and use it in GitHub Desktop.
Save riltsken/8043caec93f4219d64e578b694982917 to your computer and use it in GitHub Desktop.
async/await testing with promise.all
/*
* Theory: Does async/await block / become synchronous in promise.all where map itself contains async/await function
* Conclusion: No it does not.
*/
function ordered(num) {
let start = new Date();
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`Time elapsed for ${num}`, new Date() - start);
return resolve(num)
}, 2000)
})
}
async function withAwait() {
let mainStart = new Date();
let allPromises = [];
for(let x = 0; x < 5; x++) {
allPromises.push(() => ordered(x));
}
let v
try {
v = await Promise.all(
allPromises.map(async (f) => await f())
);
} catch (e) {
console.log(e)
}
console.log(v)
console.log('Total time elapsed for async/await', new Date() - mainStart);
}
async function withoutAwait() {
let mainStart = new Date();
let allPromises = [];
for(let x = 0; x < 5; x++) {
allPromises.push(() => ordered(x));
}
let v
try {
v = await Promise.all(
allPromises.map((f) => f())
);
} catch (e) {
console.log(e)
}
console.log(v)
console.log('Total time elapsed plain', new Date() - mainStart);
}
async function main() {
await withAwait();
await withoutAwait();
}
main();
// Time elapsed for 0 2018
// Time elapsed for 1 2022
// Time elapsed for 2 2024
// Time elapsed for 3 2024
// Time elapsed for 4 2024
// [ 0, 1, 2, 3, 4 ]
// Total time elapsed for async/await 2029
// Time elapsed for 0 2003
// Time elapsed for 1 2002
// Time elapsed for 2 2002
// Time elapsed for 3 2002
// Time elapsed for 4 2002
// [ 0, 1, 2, 3, 4 ]
// Total time elapsed plain 2004
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment