嵌套for循环MongoDB中的Javascript异步

Javascript async in nested for loop MongoDB

本文关键字:Javascript 异步 中的 MongoDB for 循环 嵌套      更新时间:2023-09-26

我在一个for循环中有一个异步函数嵌套在另一个for环路中。

// recipesArray is an array of arrays of objects
// recipeObject is an array of objects
// currentRecipe is an object
connectToDb(function(){
   // LOOP 1
   for (var i=0, l=recipesArray.length; i < l; i++) {
      // recipeObject is an 
      var recipeObject = recipesArray[i];
      // LOOP 2
      for (var x=0, y=recipeObject.length; x < y; x++) {
         var currentRecipe = recipeObject[x];
         // this is an asynchronous function
         checkRecipe(currentRecipe, function (theRecipe) {
            if (theRecipe === undefined) {
               console.log('RECIPE NOT FOUND');
            } else {
               console.log('RECIPE FOUND', theRecipe);
            }
         });
      }
   }
});

我需要根据checkRecipe函数的结果将数据添加到recipesArray中。

我一直在尝试不同的东西。。。-我是不是试着追踪我和x。。。-我是否尝试多次回调。。。-我甚至需要做所有这些吗,或者有其他方法吗。。。。

我还尝试过使用node的异步库(这实际上对其他情况很有帮助),但forEach不接受对象(只有一个数组)。

卡住了。

如有任何建议,我们将不胜感激。

假设checkRecipe()可以无限制并行运行,下面是如何使用async.each():

connectToDb(function() {
  async.each(recipesArray, function(subArray, callback) {
    async.each(subArray, function(currentRecipe, callback2) {
      checkRecipe(currentRecipe, function(theRecipe) {
        if (theRecipe === undefined)
          return callback2(new Error('Recipe not found'));
        callback2();
      });
    }, callback);
  }, function(err) {
    if (err)
      return console.error('Error: ' + err);
    // success, all recipes found
  });
});