我正在尝试弄清楚如何完成此工作流程,但似乎无法确定。我有 n 个 <select>
页面上的元素。当页面加载时,对于每个 <select>
元素,我需要做一个 $.get(...);
称呼。一旦所有这些调用 完成,然后,只有到那时我才需要运行一个额外的函数。这里有一些示例代码可以更好地解释:
function doWork(selectEl) {
var getData = ...; // build request data based on selectEl
$.get('/foo/bar', getData, function (data) {
// Do something to selectEl with the result
});
}
function doMoreWork() {
// Do something with all the selects now that they are ready
}
$(function () {
// For each of the select elements on the page
$('select').each(function(index, selectEl) {
// Go do some AJAX-fetching of additional data
doWork(selectEl);
});
// Once *all* the $.get(...) calls are done, do more things
doMoreWork();
});
使用上面的代码,doMoreWork()
通常在所有异步 $.get(...);
之前调用调用有机会返回;这不是我想要的。我需要所有 $.get(...);
在 doMoreWork()
之前完成调用可以调用。基本上我需要一个回调来执行一次所有 $.get(...);
上例中的调用已完成。
我将如何实现这一目标?
最佳答案
每次调用
doWork
时,增加一个计数器。每次返回响应时,递减计数器。
当计数器达到
0
时让回调调用doMoreWork
。
var counter = 0;
function doWork(selectEl) {
counter++;
var getData = ...; // build request data based on selectEl
$.get('/foo/bar', getData, function (data) {
counter--;
if( !counter ) { doMoreWork(); }
});
}
function doMoreWork() {
// Do something with all the selects now that they are ready
}
$(function () {
// For each of the select elements on the page
$('select').each(function(index, selectEl) {
// Go do some AJAX-fetching of additional data
doWork(selectEl);
});
});
关于javascript - 我将如何推迟这个 javascript 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7181035/