0

I'm getting "done..." before the timeout expired:

Promise.resolve(setTimeout(() => {
   console.log('print after 3 seconds')
}, 3000))
.then(console.log("done..."))

// Result:
// done...
// print after 3 seconds.

In this other example, it seems correct, so what is the difference? Or it is just a coincidence?

Promise
    .resolve(console.log("print first"))
    .then(() => {
       console.log("print second")
    })
// Result:
// print first
// print second

Any thoughts?

jfriend00
  • 580,699
  • 78
  • 809
  • 825
Phoenix
  • 367
  • 4
  • 14
  • `Promise.resolve()` doesn't wait for the `setTimeout()` to be done before advancing the promise chain. See the [Using setTimeout in Promise chain](https://stackoverflow.com/questions/39538473/using-settimeout-on-promise-chain) for how to do that properly. In fact, your question is probably a duplicate of that one and can be closed as such. – jfriend00 Nov 05 '17 at 17:55

2 Answers2

0

Window.setTimeout don't return a Promise, it returns A Number, representing the ID value of the timer that is set. Use this value with the clearTimeout() method to cancel the timer.

See https://www.w3schools.com/jsref/met_win_settimeout.asp

You are getting done because when setTimeout finish, the 3 seconds aren't elapsed yet.

rkouye
  • 433
  • 3
  • 10
0

Your usage of Promise is wrong, you should create a new Promise, and call the resolve function whenever your logic needs, at your case in the end of setTimeout.

new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('print after 3 seconds');
      resolve();
    }, 1000);
  })
  .then(() => console.log("done..."))
felixmosh
  • 20,379
  • 4
  • 36
  • 56
  • The second example "works" by mistake, cause you are invoking `console.log` on the definition, and the `then` callback always will on "different" event-loop so it will run *after* the first console.log – felixmosh Nov 05 '17 at 18:09
  • I get the `done...` first and then the `print after 3 seconds` ... !? – Philipp Kyeck May 17 '18 at 16:29
  • My mistake, you need to pass a callback to then, I've fixed the demo. – felixmosh May 17 '18 at 17:14