承诺不等待超时

时间:2017-09-25 12:09:35

标签: javascript node.js promise

我正在学习Promise库,但坚持以下问题。

//Function for getting sum
    function getSum(n1, n2) {   
       var isAnyNegative = function() {   
          return n1 < 0 || n2 < 0;   
       }
       var promise = new Promise(function(resolve, reject) {   
          if (isAnyNegative()) {   
             reject(Error("Negatives not supported"));   
          }   
          resolve(n1 + n2)
       });   
       return promise;   
    }

 ////Function for getting Difference
    function getDiff(n1,n2){
        var diff = n1-n2;
        setTimeout(function(){
            console.log("value of diff--- ", diff)
            return diff;
        }, 2000)
    }

    getSum(5,6)
    .then(function(callbackResult){
        console.log("first callback-Result- ", callbackResult)
        return getDiff(14,11);
    }, function(error){
        //handling error
    })
    .then(function(callbackResult){
        console.log("second callback--Result- ", callbackResult)
        return getSum(22,22);
    }, 
    function(error){
        //handling error
    })
    .then(function(callbackResult){
        console.log("third callback--Result- ", callbackResult)
    }, function(error){
        //handling error
    })

我为此代码段获得的输出: -

first callback-Result-  11
second callback--Result-  undefined
third callback--Result-  44
value of diff---  3

为什么没有第二次回调等待差异函数返回。我认为这是Promise库同步代码的主要特性。

2 个答案:

答案 0 :(得分:4)

您必须以异步方式处理setTimeout。例如:

function getDiff(n1,n2){
   return new Promise((resolve) => {
        const diff = n1 - n2;

        setTimeout(() => {
            console.log('value of diff--- ', diff);

            return resolve(diff);
        }, 2000);
    }
});

答案 1 :(得分:0)

因为你在超时内的匿名函数中返回 diff 。如果您想等待承诺链,您必须从 getDiff 返回Promise实例,就像之前在 getSum 中所做的那样。

function getDiff(n1,n2){
    var diff = n1-n2;
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            console.log("value of diff--- ", diff)
            resolve(diff);
        }, 2000);
    });
}