0

I am returning a Promise in an IFFE and the first thing that gets logged is first but then immediately after that third is logged and then comes second. If my setTimeout is in the then, isn't everything in there synchronously run?

(() => {
    return new Promise(resolve => {
       console.log("first")
       resolve()
    })
    .then(() => {
       setTimeout(() => console.log("second"), 3000)
    })


})()
.then(() => console.log("third"))
RicardoAlvveroa
  • 226
  • 1
  • 8

1 Answers1

0

If you want to use setTimeout in a Promise-based way you have to create another promise there and resolve it in the setTimeout callback like so:

new Promise(resolve => setTimeout(resolve, 3000));

Or in context:

new Promise(resolve => {
  console.log('first');
  resolve();
})
  .then(
    () =>
      new Promise(resolve =>
        setTimeout(() => {
          console.log('second');
          resolve();
        }, 3000)
      )
  )
  .then(() => console.log('third'));
Ricki-BumbleDev
  • 1,698
  • 1
  • 16
  • 18