Rehmat Sayany
Mar 14, 2024

--

In this case when you want to wait for the first promise to resolve and than get value from it and use it in second promise this mean you want to make it synchronise in this case.

You can achieve this using



console.log("Welcome to Coding Experience!");


async function demo() {
console.log("Start");
let startTime = Date.now();

let p1 = await new Promise((resolve) => {
setTimeout(() => resolve('result1'), 10000);
});

let p2 = new Promise((resolve) => {
setTimeout(() => resolve('result2'), 10000);
});

let result1 = await p1;
console.log("P1 resolved in", Date.now() - startTime, "ms");

let result2 = await p2;
console.log("P2 resolved in", Date.now() - startTime, "ms");

console.log("End");
}

demo();

Here p1 with take 10 second to resolve. After 10 second p2 will take another 10 second to resolve.

--

--

Rehmat Sayany
Rehmat Sayany

Written by Rehmat Sayany

Full Stack developer @westwing passionate about NodeJS, TypeScript, React JS and AWS.

No responses yet