Shiva Sai
Shiva Sai

Reputation: 463

A Better understanding on Promise.prototype.then

i Have a code something looks like this

function hello(){
     setTimeout(() => console.log("after 3sec"), 3000);
 }
  let x = Promise.resolve()
  x.then(() => {
  hello()
  }).then(() => console.log("after 1st then"))

now the output is strange , the console.log in the 2nd then function is getting executed before the console.log in the 1st then .. how to make it synchronous , i mean how can i say that 2nd .then should be executed only after the 1st .then

Upvotes: 2

Views: 58

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371128

setTimeout itself doesn't return a Promise - it's callback-based. If you want to use a callback-based function in a Promise chain, you have to explicitly convert it to a Promise:

let x = Promise.resolve()
x.then(() => {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log("after 500ms");
      resolve();
    }, 500);
  });
}).then(() => console.log("after 1st then"))

As for your new question, you'll have to make hello return a Promise, and then return the hello call so it can be chained:

function hello() {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log("after 500ms");
      resolve();
    }, 500);
  });
}
let x = Promise.resolve()
x.then(() => {
  return hello()
}).then(() => console.log("after 1st then"))

Upvotes: 3

Related Questions