尽管遭到拒绝,承诺仍会兑现

Promise fulfilled inspite of rejection

我正在使用 bluebird 结算方法来检查承诺的结果,无论是否有任何拒绝。在 secondMethod 我已经拒绝了承诺,但我仍然得到 isFulfilled() true.

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;
};

很确定 isFulfilled 指的是它是否完整,无论它是 resolved 还是 rejected

您可以使用 isRejected 之类的东西来检查承诺是否已被拒绝。

settle API 已弃用。请参考 github link and this for info. Use reflect API 而不是文档中指出的那样。

其次,documentation举例说明:

Using .reflect() to implement settleAll (wait until all promises in an array are either rejected or fulfilled) functionality

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());
    }
});

以上代码解释:

在上面的示例中,作者使用 map 遍历承诺数组,其中 returns reflect 并检查每个承诺是 isRejectedisFulfilled

我调试了你的代码,你的函数中的代码没有被调用。您需要实际调用函数 :)

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);
});