I am new to JavaScript promises. I am trying the following code:
async function handlePromises() {
var promise1 = new Promise((resolve, reject) => {
console.log(`Creating promise1 object at ${new Date(Date.now()).toISOString()}`);
setTimeout(() => {
resolve(`Promise 1 resolved after 10 seconds at ${new Date(Date.now()).toISOString()}`);
}, 10000);
});
let promise2 = new Promise((resolve, reject) => {
console.log(`Creating promise2 object at ${new Date(Date.now()).toISOString()}`);
setTimeout(() => {
resolve(`Promise 2 resolved after 5 seconds at ${new Date(Date.now()).toISOString()}`);
}, 5000);
});
let promise3 = new Promise((resolve, reject) => {
console.log(`Creating promise3 object at ${new Date(Date.now()).toISOString()}`);
setTimeout(() => {
resolve(`Promise 3 resolved after 3 seconds at ${new Date(Date.now()).toISOString()}`);
}, 3000);
});
let promise4 = new Promise((resolve, reject) => {
console.log(`Creating promise4 object at ${new Date(Date.now()).toISOString()}`);
setTimeout(() => {
resolve(`Promise 4 resolved after 4 seconds at ${new Date(Date.now()).toISOString()}`);
}, 4000);
});
return Promise.all([promise1, promise2, promise3, promise4]);
}
handlePromises();
Now I am trying to call the above function from the call of the following function:
async function handlePromisesUsingAsync() {
let getPromisesArray = handlePromises();
getPromisesArray.then((value) => console.log(value));
}
This call prints the output as expected :
But when I change the handlePromisesUsingAsync method definition to the following code(notice the addition of await keyword):
async function handlePromisesUsingAsync() {
let getPromisesArray = await handlePromises();
getPromisesArray.then((value) => console.log(value));
}
I get the following error:
Why is this so? Isn't the SAME function returning the SAME fulfilled Promise in both the calls?
CodePudding user response:
await
will wait for the then-able on its right side to resolve, and then the whole expression will evaluate to that resolved value. For example
(async () => {
const containsTwo = await Promise.resolve(2);
console.log(containsTwo);
})();
containsTwo
is not a Promise - it's the resolved value that the await
section extracted from the Promise.resolve
. containsTwo
is just a plain number.
Similarly, if you do
let getPromisesArray = await handlePromises();
getPromisesArray
is no longer an array of Promises, but an array of resolve values, since you await
ed the Promise.all
call.
When going through code, you can think of await
as turning Promises into what they resolve to, without leaving the Promises behind (unless something else already has a reference to the created Promise).
All you need is
const results = await handlePromises();
console.log(results);