Promise 不等待超时 [英] Promise does not wait for timeout

查看:73
本文介绍了Promise 不等待超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Promise 库,但遇到了以下问题.

I am learning Promise library but stuck on the following problem.

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

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

The output I am getting for this code snippet:-

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

为什么第二个回调不等待差异函数返回.我认为这是 Promise 库同步代码的主要功能.

Why doesn't second callback wait for the difference function to return. I think this is the main feature of Promise library to Synchronize the code.

推荐答案

你必须以异步方式处理 setTimeout.例如:

You gotta deal with setTimeout in an asynchronous way. For example :

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

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

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

这篇关于Promise 不等待超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆