繁体   English   中英

AJAX异步回调正常工作,但是如何等待返回的值

[英]AJAX asynch callback working correctly but how do I wait for the returned values

我主要的EXTJS函数正在调用三个不同的AJAX异步函数,好消息是每个AJAX函数都成功返回了有关AJAX GET调用是否成功的布尔回调。

问题-一旦所有三个AJAX函数都返回了布尔结果,我就需要从我的主调用函数中执行附加的后期处理逻辑。

但是由于它是异步的,所以代码将不会等待异步功能完成而飞走。

关于如何将代码添加到GRACEFULLY的任何想法都等到typeof状态不再为'undefined'为止?

我现在不在我的代码旁,但这是一个大概的近似值。

function main(){
  var status1, status2, status3, result1, result2,result3;

    thisIsAsynchFunction1(args,function(result1){
        status1 = result1;
    });
    thisIsAsynchFunction2(args,function(result1){
        status2 = result1;
    });

    thisIsAsynchFunction1(args,function(result1){
        status3 = result1;
    });

    // Perform logic based on callback from functions above

}

谢谢。

您不能等待Javascript。 这样根本行不通。 当发现所有三个异步结果都已完成时,您可以做的是触发最终操作。 无需重新设计代码以使用Promise(这是实现此目标的现代方法),您可以执行以下操作:

function main(callbackFn){
  var status1, status2, status3, doneCnt = 0;

    thisIsAsynchFunction1(args,function(result1){
        status1 = result1;
        ++doneCnt;
        checkDone();
    });
    thisIsAsynchFunction2(args,function(result1){
        status2 = result1;
        ++doneCnt;
        checkDone();
    });

    thisIsAsynchFunction1(args,function(result1){
        status3 = result1;
        ++doneCnt;
        checkDone();
    });

    // Perform logic based on callback from functions above
    function checkDone() {
        // if all three results are done, then call the callback
        if (doneCnt === 3) {
            callbackFn(status1, status2, status3);
        }
    }
}

// call main and pass it a callback function
main(function(s1, s2, s3) {
    // all three async results are available here
});

// Be careful because code here will execute BEFORE the async results are done
// any code that must wait for the async results must be in the above callback

一种较新的方法是让每个异步操作返回一个promise,当每个异步操作完成时,它将用其结果来解决其promise。 然后,您可以使用Promise库函数(通常在调用所有三个.when()调用.when()来触发回调。许多现代JS库已经从Ajax调用(例如jQuery)返回Promise,因此Promise已经存在。

我本人不了解ExtJS,但查看了它的文档,还没有看到Promise支持,我找到了一个线程来讨论Promise不会在版本5中的事实。因此,也许您可​​以使用计数器设计以上,或者ExtJS拥有自己的一些支持,可以监视何时完成多个异步操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM