打破javascript嵌套的async.each循环,但继续主循环

时间:2014-05-10 15:55:01

标签: javascript node.js loops asynchronous async.js

我有一组名为recipesArray的对象数组。

recipesArray = [  [{name = "the recipe name", url = "http://recipeurl.com"},
                   {name = "the other neame", url = "http://adifferenturl.com"},
                   {name = "another recipe", url = "http://anotherurl.com"}],

                   [{name = "the recipe name", url = "http://recipeurl.com"},
                   {name = "the other neame", url = "http://adifferenturl.com"},
                   {name = "another recipe", url = "http://anotherurl.com"}],

                   [{name = "the recipe name", url = "http://recipeurl.com"},
                   {name = "the other neame", url = "http://adifferenturl.com"},
                   {name = "another recipe", url = "http://anotherurl.com"}] ]

我想要打破这个嵌套的async.each循环,但继续主async.each循环。

// main async.each
async.each(recipes, function(subArray, callback1) {
   // nested async.each
   async.each(subArray, function(theCurrentRecipe, callback2) {
      checkHREFS(theCurrentRecipe, function(thisRecipe) {
         if ('i have a conditional here') {
            // break out of this nested async.each, 
            // but continue the main async.each.
         } else {
            // continue
         }
         callback2();
      });
   }, callback1);
}, function(err) {
if (err) {
   return console.error(err);

   // success, all recipes iterated
});

2 个答案:

答案 0 :(得分:7)

一种方法可能是修改内部each()的最终回调,以检查具有特殊属性的Error对象,该属性指示您提前分解并且它不是真正的错误。然后在条件内部,将具有该属性集的Error对象传递给回调。

示例:

// main async.each
async.each(recipes, function(subArray, callback1) {
  // nested async.each
  async.each(subArray, function(theCurrentRecipe, callback2) {
    checkHREFS(theCurrentRecipe, function(thisRecipe) {
      if ('i have a conditional here') {
        // break out of this nested async.each, 
        // but continue the main async.each.
        var fakeErr = new Error();
        fakeErr.break = true;
        return callback2(fakeErr);
      }
      // continue
      callback2();
    });
  }, function(err) {
    if (err && err.break)
      callback1();
    else
      callback1(err);
  });
}, function(err) {
  if (err)
    return console.error(err);

  // success, all recipes iterated
});

答案 1 :(得分:1)

// inner async.each (simplificated)
  async.each(subArray, function(theCurrentRecipe, callback2) {
    checkHREFS(theCurrentRecipe, function(thisRecipe) {
      if ('i have a conditional here') {
        // going to break out of this nested async.each
        return callback2({flag:true}); // It doesn't have to be an "new Error()" ;-)
      }
      // continue
      callback2();
    });
  }, function(msg) {
    if (msg && msg.flag) // Here CHECK THE FLAG
      callback1(); // all good!... we brake out of the loop!
    else
      callback1(msg); // process possible ERROR.
  });