代码:
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' );
});
输出:
all done
x done
预期输出:
x done
all done
为什么承诺x
在调用下一个then
回调之前没有等待解决?
JSFiddle :https://jsfiddle.net/puhbqtu0/1/
答案 0 :(得分:5)
因此,如果您希望在系列中运行promises,则应将x
转换为函数并在then
中调用它:
function x() {
return new Promise(resolve => {
setTimeout(() => {
console.log('x done');
resolve()
}, 1000);
});
});
Promise.resolve()
.then(x)
.then(() => console.log('all done'));
或最简单的变体:
x().then(() => console.log('all done'));