1

I am learning JS promises. I am kinda confused on how to reslove the promise returned by f2 only after running the cb function which takes 5 seconds.

var cb = function(){
  console.log('5 sec');
}

var f2 = function(){
    return new Promise((resolve,reject)=>{
      setTimeout(cb, 5000);
      console.log('Last line of f2')
     resolve('5RESOLVED')
    });
}

f2().then(res=>{
  console.log(res)
})

The current output is in the following order

  • Last line of f2
  • 5RESOLVED
  • 5 sec

I want the output to be - Last line of f2 - 5 sec -5Resolved

1 Answers1

5

You need to place the resolve(…) call inside the asynchronous cb, so that it happens only after 5 seconds. Currently you are calling it immediately (after having scheduled the callback). Use

function f2() {
  return new Promise((resolve,reject) => {
    setTimeout(function() {
      console.log('5 sec');
      resolve('5RESOLVED')
    }, 5000);
    console.log('Last line of f2');
  });
}

Even better, I would recommend to not write any asynchronous callbacks yourself (which is error-prone), but only deal with promise-based helper functions:

function delay(t) {
  return new Promise(resolve => {
    setTimeout(resolve, t);
  });
}
async function f2() {
  console.log("last line of f2");
  await delay(5000);
  console.log("5 sec");
  return "5RESOLVED";
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375