内部forEach循环内部的ajax,在内部回调触发后完成

Dan*_*iel 3 javascript ajax node.js

我有一个ajax调用,它位于另一个函数内的forEach循环中.问题是,外部函数的回调在内部循环结束之前触发 - 因此"staticItemList"在传递给回调时没有填充项目.我该如何解决这个问题?我真的花了很多时间.谢谢.

  exports.buildTheList = function (parsedList, callback) {
        var staticItemList = {};
        parsedList.forEach(function(parsedItem) { 

                db.staticList.find({"_id":parsedItem.ID}).forEach(function(err, doc) {
                    if (!doc){
                        console.log("newStaticItem not found in db");
                        parsedDataFetcher.fetchParsedDetails(Path, function(parsedDetails){
                            staticItemList["_id"] = parsedItem.ID;
                            staticItemList[parsedItem.ID] = {
                                    "_id": parsedItem.ID,
                                    "type": parsedItem.type,
                                     } 
                                 })

                             }else {
                                   console.log("newStaticItem already found in db");
                             } 
                 });
             });


         callback(staticItemList);
     }
Run Code Online (Sandbox Code Playgroud)

sya*_*ani 5

在循环内添加一个计数器变量,并在每次异步方法完成时减少它.一旦计数器达到零,就调用回调.在伪代码中:

 var counter = 0;
 foreach(function() {
     counter++;
     doAsync(function() {
           // add to list

           counter--;
           if (counter === 0) {
               callback(list);
           }
     });
 }
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.