我在搜索函数中有一个 for 循环,有一个在循环内执行回调的函数,我想在循环之后以及所有回调完成后执行 BUILD() 函数。我不确定该怎么做,因为循环在所有回调完成之前就结束了。回调是用于获取数据的 API 请求,我想使用该数据进行 BUILD()。
我阅读了有关 deferred 的内容,因此我尝试将 for 循环放在一个函数中以用于 deferred,然后在“.then( ... )”上调用 BUILD()。但这似乎不起作用 - 我想我理解错了。
帮助?!
请注意,这是使用 Google Maps Places API(搜索和获取详细信息)。
var types = {
'gym' : 'fitness, gym',
'grocery_or_supermarket': ''
}
function search() {
for (var key in types) {
var request = { ... };
service.search(request, searchCallback);
}
// PROBLEM AREA
BUILD();
}
function searchCallback(results, status) {
for (var i = 0; i < results.length; i++) {
var request = { ... };
service.getDetails(request, detailsCallback);
}
}
function detailsCallback(place, status) {
// add place marker to maps and assign info window and info window event
}
最佳答案
只要稍微修改一下代码,就可以实现。
var total = 1337; // Some number
var internal_counter = 0;
var fn_callback = function() {
searchCallback.apply(this, arguments);
if (++internal_counter === total) {
BUILD();
}
};
for (var i=0; i<total; i++) {
service.search(request, fn_callback);
...
解释
首先,我们创建一个本地函数和变量。
- 该变量是一个计数器,在调用回调时增加。
- 该函数被传递给调用原始回调的异步方法 (
service.search
)。增加计数器后,根据保存迭代总数的变量检查计数器的值。如果它们相等,则调用结束函数 (BUILD
)。
复杂案例:处理嵌套回调。
var types = { '...' : ' ... ' };
function search() {
var keys = Object.keys(types);
var total = keys.length;
// This counter keeps track of the number of completely finished callbacks
// (search_callback has run AND all of its details_callbacks has run)
var internal_counter = 0;
for (var i=0; i<total; i++) {
var request = { '...' : ' ... ' };
services.search(request, fn_searchCallback);
}
// LOCAL Function declaration (which references `internal_counter`)
function fn_searchCallback(results, status) {
// Create a local counter for the callbacks
// I'm showing another way of using a counter: The opposite way
// Instead of counting the # of finished callbacks, count the number
// of *pending* processes. When this counter reaches zero, we're done.
var local_counter = results.length;
for (var i=0; i<results.length; i++) {
service.getDetails(request, fn_detailsCallback);
}
// Another LOCAL function (which references `local_counter`)
function fn_detailsCallback(result, status) {
// Run the function logic of detailsCallback (from the question)
// " ... add place marker to maps and assign info window ... "
// Reduce the counter of pending detailsCallback calls.
// If it's zero, all detailsCallbacks has run.
if (--local_counter === 0) {
// Increase the "completely finished" counter
// and check if we're finished.
if (++internal_counter === total) {
BUILD();
}
}
} // end of fn_detailsCallback
} // end of fn_searchCallback
}
功能逻辑在注释中解释。我在本节的标题前加了“复杂”作为前缀,因为该函数使用了嵌套局部 函数和变量。视觉解释:
var types, BUILD;
function search
var keys, total, internal_counter, fn_searchCallback;
function fn_searchCallback
var result, status; // Declared in the formal arguments
var local_counter, i, fn_detailsCallback;
function fn_detailsCallback
var result, status; // Declared in the formal arguments
在上图中,每个缩进级别都表示一个新的scope Explanaation on MDN。 .
当一个函数被调用时,比方说 42 次,就会创建 42 个新的本地作用域,它们共享相同的父作用域。在一个范围内,declared variables对父作用域不可见。尽管父作用域中的变量可以被“子”作用域中的变量读取和更新,前提是您没有声明具有相同名称的变量。我的答案功能中使用了此功能。
关于javascript - for 循环中的回调完成后如何执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11275999/