我想在foreach
完成后执行回调,但它不能正常工作。我该怎么做呢?
var response = [];
myArray.forEach(function(data) {
data.asyncFunction(function(result) {
response.push(result);
});
}, function() {
console.log(response); // Not being called.
});
console.log(response); // (Empty) Executed before foreach finish.
因为foreach
只接受一个回调
。由于您正在foreach
中调用异步方法,因此需要检查是否完成了所有asyn调用
var response = [];
myArray.forEach(function(data, index) {
data.asyncFunction(function(result) {
response.push(result);
if(response.length === myArray.length) {
//foreach work done
}
});
});
试试看:
myArray.forEach(function(element, index, array){
asynchronous(function(data){
if (index === myArray.length - 1) {
response.push(data);
functionAfterForEach();
}
})
});