Reputation: 67
const function1 = () =>
new Promise(function(resolve,reject) {
setTimeout(() => {
resolve(10)
},6000)
});
const function2 = async () => {
console.log("first");
const val = await function1()
console.log("second");
return val
}
console.log("third -- " ,function2())
I was exepecting the order of the message as below:
first
second
third -- Promise { <pending> }>
But it turns out to give the below output:
first
third -- Promise { <pending> }
second
can anyone please help me understanding this ?
Upvotes: 0
Views: 89
Reputation: 11
rather than calling function2()
you need to await
on it
await function2(); // logs first (6 seconds expire) second, 10
this is because you need to wait for function 2 to resolve the Promise before proceeding
you could do the following for the desired result
const function3 = async () => {
const third = await function2();
console.log( "third --", third )
}
function3();
Upvotes: 1
Reputation: 169
Try next code
const function1 = () =>
new Promise(function (resolve, reject) {
setTimeout(() => {
resolve(10)
}, 6000)
});
const function2 = async () => {
console.log("first");
const val = await function1()
console.log("second");
return val;
}
const start = async () => {
console.log("third -- ", await function2());
};
start();
Upvotes: 0
Reputation: 4346
explanation of your code
console.log("first"); - goes first, I hope that there is no questions
when interpretator see this line const val = await function1()
- it waits here and continue to execute synchronous code with is console.log("third -- " ,function2())
and you can see third -- Promise { <pending> }
than promise is resolving and execution of async part continues and you finally can see console.log("second");
to achieve expected behavior try this:
const function1 = () =>
new Promise(function(resolve,reject) {
setTimeout(() => {
resolve(10)
},6000)
});
const function2 = async () => {
console.log("first");
const val = function1()
console.log("second");
return val
}
console.log("third -- " , function2())
Upvotes: 0
Reputation: 882
It's in the logs buddy :)!
The log with the word third is logged second. Because the log with the word 'second' is resolved inside function2 which is called as a normal function. This code basically assumes you're not interested in the (async) result of function two, so it just retuns the pending promise.
Whenever you want the result (and not the pending promise) of an async function you should always await
it of chain a then()
where you can log the final result, which in this case is 10.
Upvotes: 0