Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise not waiting to resolve before next then

Code:

var x = new Promise((resolve, reject) => {
    setTimeout( function() {
        console.log( 'x done' );
        resolve()
    }, 1000 );
});


Promise.resolve().then(x).then((resolve, reject) => {
    console.log( 'all done' );
});

Output:

all done
x done

Expected output:

x done
all done

Why is the promise x not waiting to resolve before calling the next then callback?

JSFiddle: https://jsfiddle.net/puhbqtu0/1/

like image 804
HyderA Avatar asked Jan 07 '23 04:01

HyderA


1 Answers

So as you want to run promises in a series you should convert x to function and call it in then:

function x() {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('x done');
      resolve()
    }, 1000);
  });
});

Promise.resolve()
  .then(x)
  .then(() => console.log('all done'));

or simplest variant:

x().then(() => console.log('all done'));

jsfiddle demo

like image 191
alexmac Avatar answered Jan 19 '23 06:01

alexmac