承诺尽管遭到拒绝仍然履行

时间:2017-11-13 07:58:59

标签: javascript node.js bluebird

我正在使用bluebird结算方法来检查承诺的结果,而不管任何拒绝。在 secondMethod 中,我拒绝承诺,我仍然 isFulfilled()为真。

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

3 个答案:

答案 0 :(得分:2)

非常确定isFulfilled指的是否完整,无论是resolved还是rejected

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

settle API已被弃用。有关信息,请参阅github链接和this。请使用reflect API,如文档中所示。

其次,documentation指出了一个例子:

  

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

上述代码说明:

在上面的示例中,作者使用map迭代承诺数组,返回reflect并检查每个承诺是isRejected还是isFulfilled