我试图在项目中使用 JavaScript promise ,但事件的顺序是意外的。我已使用测试 promise 将其缩小为一个小型演示。
testPromises = function(promiseNum){
return new Promise(function(resolve, reject) {
console.log ('handling promise '+promiseNum);
setTimeout(function(){
console.log("resolving testPromises "+promiseNum);
resolve();
},2000)
});
};
然后我这样调用它:
testPromises(1).then(testPromises(2)).then(testPromises(3))
.then(function(value) {
console.log('all promises resolved');
}, function(reason) {
console.log('some promise was rejected');
});
这是控制台输出:
handling promise 1
handling promise 2
handling promise 3
resolving testPromises 1
all promises resolved
resolving testPromises 2
resolving testPromises 3
我怎样才能得到输出:
handling promise 1
resolving testPromises 1
handling promise 2
resolving testPromises 2
handling promise 3
resolving testPromises 3
all promises resolved
最佳答案
.then()
需要一个函数引用。当你做这样的事情时:
.then(testPromises(2))
您正在立即执行函数 testPromise()
并将返回值传递给 .then()
。这几乎不是你想要的(除非 testPromises()
返回另一个函数)因为要让 .then()
完成它的工作,你必须向它传递一个函数引用(一个它可以稍后调用的函数)。如果您立即执行该函数,则 .then()
无法完成其工作并稍后调用它。
相反,你想要的是:
.then(function() {
return testPromises(2);
})
或者,您可以使用 .bind()
:
.then(testPromises.bind(null, 2))
因此,您的整个链条将如下所示:
testPromises(1).then(function() {
return testPromises(2);
}).then(function() {
return testPromises(3);
}).then(function(value) {
console.log('all promises resolved');
}, function(reason) {
console.log('some promise was rejected');
});
或者,使用 .bind()
testPromises(1)
.then(testPromises.bind(null, 2))
.then(testPromises.bind(null, 3))
.then(function(value) {
console.log('all promises resolved');
}, function(reason) {
console.log('some promise was rejected');
});
如果您经常这样做,您可以为 testPromises()
制作一个 curry 包装器,它会返回另一个函数。这本质上就是上面的 .bind()
所做的,但是一旦声明了包装函数,语法就更易于使用了。
function tp(arg) {
return function() {
return testPromises(arg);
}
}
然后,因为该包装器返回另一个函数,您可以执行以下操作:
testPromises(1).then(tp(2)).then(tp(3))
.then(function(value) {
console.log('all promises resolved');
}, function(reason) {
console.log('some promise was rejected');
});
关于javascript - 为什么 Javascript promise 会乱序解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40228209/