Please have a look at the below javascript code. When I run this code in browser console window the below mentioned output is received. I am new to javascript and promises. Please help me understand how "resolved" got printed in browser console?
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall();
OUTPUT in browser console:
calling
resolved
Now my question is why "resolved" got printed in console? As of what I know is then() method should have executed when resolve() method is called.
await
operator is used to wait for the Promise
to settle. It returns the fulfilled value of the Promise
or the value itself if its not a Promise
.
In your code, since resolveAfter2Seconds()
function returns a Promise
, so in the following statement
const result = await resolveAfter2Seconds();
javascript waits for the Promise
to settle and then assigns its fulfillment value, i.e. 'resolved'
to the result
constant. After that, you log the result
on the console which is why 'resolved'
gets logged on the console.
Comments above each statement in the asyncCall
function will help you understand the output.
async function asyncCall() {
// log 'calling' on the console
console.log('calling');
// wait for the promise to resolve and then
// assign the fulfillment value to 'result'
const result = await resolveAfter2Seconds();
// log the value with which promise returned
// by 'resolveAfter2Seconds' function resolved
console.log(result);
}
As of what I know is then() method should have executed when resolve() method is called.
I can't see where you have called .then()
method in your code. .then()
method is invoked if you register any callback calling .then()
method on any Promise
.
Instead of using async-await
syntax, you could change your code as shown below to see that callback registered using .then()
is invoked after 2 seconds.
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
// store the promise returned by 'resolveAfter2Seconds' function
const p = resolveAfter2Seconds();
// register a callback function to be invoked after 2
// seconds with the resolved value
p.then(resolvedValue => {
console.log('callback invoked');
console.log('Promise resolved with the value of: ' + resolvedValue);
}).catch(error => console.log(error));
Its clear from your question that you are confused about the output of the code because it uses async-await
syntax instead of promise-chaining
. async-await
is syntactic sugar over the regular promise code that uses .then()
method calls.
I suggest that you visit the following links to understand how async-await
syntax works. Once you understand that, you will be able to understand the output.