function delay(count) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(1000);
}, count);
});
}
async function method1() {
let val = 0;
console.log("one");
val = delay(3000);
console.log("two")
return val;
}
method1().then(function(result) {
console.log(result);
});
Above is my example code.
First of all, I didn't use await delay() and this is what I intended.
First, the expected flow of writing the above code is as follows:
- console.log("one")
- console.log("two")
- return val;
- console.log(result)
- resolve(1000);
But the reality was different. The actual execution result is as follows.
- console.log("one")
- console.log("two")
- resolve(1000)
- return val;
- console.log(result)
The reason I expected return val to be executed first is because
This is because we believed that the rest of the code would be
executed while the delay() function proceeded with asynchronous
communication. However, in reality, the return is not performed until delay() is
finished.
If I use await delay() Pause at delay(). After that setTimeout exits,console.log("two") is executed and I fully understand this concept .
However, if await is not used, the rest of the code is executed, but
why is the return not executed until delay() is finished?