const wait = function () {
return new Promise(function (resolve, reject) {
resolve()
setTimeout(console.log('a'), 5000)
})
}
wait().then(() => console.log('b'))
Explain the code:
As you can see above, i created a wait()
function that return a promise, and in this function, the resolve()
will be executed immediately, and a timer that will log 'a' message after 5 seconds.
What I expected:
So what i expected is that the then()
method will be executed, it move to the then()
method immediately, so from here it will log the 'b' message. And because of 5 seconds timer waiting in the background, in the Web API, the 'a' message will be log after the 'b' message.
What it actually did:
But the result is so different, the 2 messages are both logged at the same time immediately and the 'a' is before the 'b', the 5 seconds didn't pass yet. Can you guys help me to explain, i dont really understand, i think my understand of the then()
method is wrong, so please help me to repair if you know, thank you so much!