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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With