我正在使用蓝鸟结算方法来检查承诺的结果,无论是否有任何拒绝。在第二种方法中,我拒绝了承诺,但我仍然得到 是 Ful(( 真的。
var Promise = require('bluebird');
Promise.settle([firstMethod, secondMethod]).then(function(results){
console.log(results[0].isFulfilled());
console.log(results[1].isFulfilled());
// console.log(results[1].reason());
}).catch(function(error){
console.log(error);
});
var firstMethod = function() {
var promise = new Promise(function(resolve, reject){
setTimeout(function() {
resolve({data: '123'});
}, 2000);
});
return promise;
};
var secondMethod = function() {
var promise = new Promise(function(resolve, reject){
setTimeout(function() {
reject((new Error('fail')));
}, 2000);
});
return promise;
};
我调试了您的代码,但函数中的代码未被调用。您需要实际调用函数:)
Promise.settle([firstMethod(), secondMethod()]).then(function (results) {
console.log(results[0].isFulfilled()); // prints "true"
console.log(results[1].isFulfilled()); // prints "false"
console.log(results[1].reason()); // prints "fail"
}).catch(function (error) {
console.log(error);
});
很确定isFulfilled
指的是它是否完整,无论它是resolved
还是rejected
。
您可以使用类似 isRejected
的内容来检查承诺是否被拒绝。
settle
API 已被弃用。有关信息,请参阅 github 链接和此信息。请改用reflect
API,如文档中所示。
其次,文档通过一个例子指出:
使用
.reflect()
实现settleAll
(等到数组中的所有承诺都被拒绝或实现(功能
var promises = [getPromise(), getPromise(), getPromise()];
Promise.all(promises.map(function(promise) {
return promise.reflect();
})).each(function(inspection) {
if (inspection.isFulfilled()) {
console.log("A promise in the array was fulfilled with", inspection.value());
} else {
console.error("A promise in the array was rejected with", inspection.reason());
}
});
以上代码说明:
在上面的示例中,作者使用返回reflect
的map
遍历承诺数组,并检查每个承诺是否isRejected
或isFulfilled
。