Reputation: 920
Consider the below code,
// Function which returns a promise and resolves in 2 seconds
const promiseFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
};
// Asynchronous function 1
const asyncFunction1 = async() => {
console.log(await promiseFunction());
console.log(await promiseFunction());
console.log(await promiseFunction());
}
// Asynchronous function 2
const asyncFunction2 = async() => {
let a = promiseFunction();
let b = promiseFunction();
let c = promiseFunction();
console.log(await a);
console.log(await b);
console.log(await c);
}
I am trying to understand the behaviour between asyncFunction1 and asyncFunction2 execution, the asyncFunction1 takes 2 seconds for each await (total 6) when not assigned to a variable, but asyncFunction2 resolves all the 3 promises in total 2 seconds when assigned to a variable, what happens here when it is assigned to a variable? (and we still use await with the variable).
Upvotes: 5
Views: 1131
Reputation: 1527
The callback function passed in the Promise constructor is started to execute when the promise is created(This is the main difference between Observable and Promise). Please take a look at the first code.
// Asynchronous function 1
const asyncFunction1 = async() => {
console.log(await promiseFunction());
console.log(await promiseFunction());
console.log(await promiseFunction());
}
This function waits for 2 minutes for each function so it would take 6 seconds. While the second function doesn't work the same way.
// Asynchronous function 2
const asyncFunction2 = async() => {
let a = promiseFunction();
let b = promiseFunction();
let c = promiseFunction();
console.log(await a);
console.log(await b);
console.log(await c);
}
It executes the 3 callback functions simultaneously. It works exactly like await Promise.all(). Therefore asyncFunction2 would be resolved in about 2 seconds.
Upvotes: 2
Reputation: 22490
For
asyncFunction1
asyncFunction2
Check my below console .you can see the different
const promiseFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
};
// Asynchronous function 1
const asyncFunction1 = async() => {
console.log(await promiseFunction(),1);
console.log(await promiseFunction(),1);
console.log(await promiseFunction(),1);
}
// Asynchronous function 2
const asyncFunction2 = async() => {
let a = promiseFunction();
let b = promiseFunction();
let c = promiseFunction();
console.log(await a,2);
console.log(await b,2);
console.log(await c,2);
}
asyncFunction1();
asyncFunction2();
Upvotes: 1
Reputation: 138234
The timers start when you call promiseFunction()
, thus when you await a
, all three timers are already running. Then when a
finishes after 2 seconds, the other ones are already done too.
Upvotes: 5