提问者:小点点

完成时Foreach回调[重复]


我想在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.

共2个答案

匿名用户

因为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();
       }
  })
});