0
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!

crg
  • 4,284
  • 2
  • 29
  • 57
Gia Phu Tang
  • 101
  • 6

2 Answers2

2
  1. You call wait()
  2. wait creates a new Promise
  3. resolve() immediately resolves that promise, but the function resolve appears in continues to run before the anything is done about that
  4. You call console.log('a') (assuming the missing ) is a typo in the question and not the real code) which logs a
  5. The return value of console.log (which is undefined) is passed to setTimeout (which does nothing because it isn't a function).
  6. The function ends
  7. The promise resolution takes place
  8. The then function is called
  9. console.log('b') logs b.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-2

you just have errors in how u call setTimeout

const wait = function() {
  return new Promise(function(resolve, reject) {
    resolve()
    setTimeout(() => console.log('a'), 5000)
  })
}

wait().then(() => console.log('b'))
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • While this code may answer the question, providing additional context regarding *how* and/or *why* it solves the problem would improve the answer's long-term value. – Ivar May 21 '21 at 11:20