Search code examples
javascriptangularpromiseangular-promisees6-promise

resolve() and then() comming first than async stuff


I read a guide about promise that says:

const promise = new Promise((resolve, reject) => {

// Do some async stuff

// If async opp successful
resolve();

// If async opp fails
reject();

});

So, I'm trying to use that, but with no success:

let async = new Promise((resolve, reject)=>{
  this.getPerson(page).subscribe( data => {
    console.log("First")
  });
  resolve();
})
async.then((result) =>{
  console.log("Last")
});

At console, I have the "Last" coming first, someone have a tip for me?


Solution

  • You are resolving promise before your query is completed. check below code for correct place of resolve

    let async = new Promise((resolve, reject)=>{
      this.getPerson(page).subscribe( data => {
        console.log("First");
        resolve(); // this is the expected place
      });
    });
    async.then((result) =>{
      console.log("Last")
    });