Saturday, October 15, 2022

How Promise.all works

Promise.all waits till all the promises passed to it are resolved. Here is an example code snippet:


async function fun1() {
console.log("1 before wait");
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("1 after wait");
resolve();
}, 3000);
});
}

async function fun2() {
console.log("2 before wait");
return new Promise((resolve, reject) => {
return setTimeout(() => {
console.log("2 after wait");
resolve();
}, 2000);
});
}

async function main() {
console.log("start");
await Promise.all([fun1(), fun2()]);
console.log("end");
}
main();

The above snippet outputs
start
1 before wait
2 before wait
2 after wait
1 after wait
end

No comments:

Post a Comment