对你的代码稍加修改,就可以实现。
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
}
函数逻辑在 cmets.我在本节的标题前加上了“复杂”,因为该函数使用了嵌套的局部函数和变量。视觉解释:
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 对父范围不可见。虽然父作用域中的变量可以被“子”作用域中的变量读取和更新,前提是你没有声明一个同名的变量。此功能用于我的答案功能。