Javascript 如何在调用 Ajax 等异步调用时让代码等待
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14031421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make code wait while calling asynchronous calls like Ajax
提问by thecodeHyman
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');
}
What I have tried?
我尝试过什么?
1Jquery.when()
1Jquery.when()
tried using it..it works fine. But not the way I want. $.whenwill wait but the code next to $.when()runs with out waiting. The code inside do callbackonly runs after ajax calls
尝试使用它..它工作正常。但不是我想要的方式。$.when将等待,但旁边的代码$.when()运行而无需等待。里面的代码do callback只在ajax调用后运行
2.setTimeOut() with a global flag
2.带有全局标志的 setTimeOut()
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
Not able to make any fiddle as it needs AJAX calls
无法制作任何小提琴,因为它需要 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...
编辑:正如许多人建议回调somewait()......我知道他们......但旁边的代码仍然会被执行......我希望浏览器完全停止执行旁边的代码,somewait()直到ajax调用......这也可能是一个不好的做法但如果可能的话,值得了解和尝试......
采纳答案by Dogbert
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');
}
This will print Pass1immediately (assuming ajax request takes atleast a few microseconds), then print Pass2when the onAjaxSuccessis executed.
这将Pass1立即打印(假设 ajax 请求至少需要几微秒),然后Pass2在onAjaxSuccess执行时打印。
回答by Alexander
Why didn't it work for you using Deferred Objects? Unless I misunderstood something this may work for you.
为什么它不适合你使用Deferred Objects?除非我误解了一些东西,否则这可能对你有用。
/* AJAX success handler */
var echo = function() {
console.log('Pass1');
};
var pass = function() {
$.when(
/* AJAX requests */
$.post("/echo/json/", { delay: 1 }, echo),
$.post("/echo/json/", { delay: 2 }, echo),
$.post("/echo/json/", { delay: 3 }, echo)
).then(function() {
/* Run after all AJAX */
console.log('Pass2');
});
};?
UPDATE
更新
Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property asyncto falsein your $.ajaxrequests to make them blocking. This will hang your browser until the request is finished though.
根据您的输入,您最快的选择似乎是使用同步请求。您可以将属性设置async到false您的$.ajax请求,使它们阻塞。这将挂起您的浏览器,直到请求完成。
Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.
请注意,我不建议这样做,我仍然认为您应该在基于事件的工作流中修复您的代码,以免依赖它。
回答by Amadan
Real programmers do it with semaphores.
真正的程序员是用信号量来做这件事的。
Have a variable set to 0. Increment it before each AJAX call. Decrement it in each success handler, and test for 0. If it is, you're done.
将变量设置为0. 在每次 AJAX 调用之前增加它。在每个成功处理程序中递减它,并测试0. 如果是,你就完成了。
回答by HMarioD
If you need wait until the ajax call is completed all do you need is make your call synchronously.
如果您需要等到 ajax 调用完成,您只需要同步进行调用。

