[英]Javascript Promise not waiting to resolve before next Then()
[英]Promise not waiting to resolve before next then
码:
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
不等待调用next之前解决then
回调?
JSFiddle : https : //jsfiddle.net/puhbqtu0/1/
因此,当你想在一个系列中运行promises时,你应该将x
转换为function并在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'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.