如何在调用Ajax之类的异步调用时使代码等待 [英] How to make code wait while calling asynchronous calls like Ajax

查看:131
本文介绍了如何在调用Ajax之类的异步调用时使代码等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似这样的东西

I am looking for something like this

function someFunc() {

callAjaxfunc(); //may have multiple ajax calls in this function
someWait(); // some code which waits until async calls complete
console.log('Pass2');

}

function callAjaxfunc() {
  //All ajax calls called here
  console.log('Pass1');

}

我尝试了什么?

1
Jquery.when()

1 Jquery.when()

尝试使用它..工作正常。但不是我想要的方式。 $。当将等待,但 $。when()旁边的代码在等待时运行。 内部的代码回调仅在ajax调用后运行

tried using it..it works fine. But not the way I want. $.when will wait but the code next to $.when() runs with out waiting. The code inside do callback only runs after ajax calls

2。
带有全局标志的setTimeOut()

2. setTimeOut() with a global flag

我非常有信心这将起作用。我试过跟随。

I was so confident this will work. I tried like following.

GlobalFlag = false;

function someFunc()     
    callAjaxfunc(); //may have multiple ajax calls in this function
    setTimeOut(waitFunc, 100); // some  which waits until async calls complete
    console.log('Pass2');
}

function callAjaxfunc() {
    //All ajax calls called here
    onAjaxSuccess: function() {
        GlobalFlag = true;
    };
    console.log('Pass1');    
}

function waitFunc() {
    if (!GlobalFlag) {
        setTimeOut(waitFunc, 100);
    }
}​

仍然无法得到想要的结果。我在这里做错了吗?这不是方法吗?

Still not able to get wanted result. Am I doing something wrong here? This is not the way?

我想要的结果应该是这样的

Result I wanted should come like this

Pass1
Pass2

因为需要AJAX调用所以无法做任何小提琴

Not able to make any fiddle as it needs AJAX calls

编辑:正如许多人建议回调......我知道他们......但仍然是旁边的代码somewait() 将被执行...我希望浏览器完全停止执行 somewait()旁边的代码,直到ajax调用..也可能是不好的做法,但值得知道并尽可能尝试...

EDIT: As many were suggesting callbacks..i know about them..but still the code next to somewait() will get executed...I want browser to completely stop executing code next to somewait() until the ajax call..Also it may be a bad practice but worth to know and try if possible...

推荐答案

使用回调。这样的事情应该基于你的示例代码。

Use callbacks. Something like this should work based on your sample code.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

这将打印 Pass1 立即(假设ajax请求至少需要几微秒),然后在执行 onAjaxSuccess 时打印 Pass2

This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.

这篇关于如何在调用Ajax之类的异步调用时使代码等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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