Break out of javascript nested async.each loop but continue main loop

后端 未结 2 1082
庸人自扰
庸人自扰 2021-01-06 17:08

I have an array of arrays of objects called recipesArray.

recipesArray = [  [{name = \"the recipe name\", url = \"http://recipeurl.com\"},
                           


        
2条回答
  •  没有蜡笔的小新
    2021-01-06 17:48

    One way might be to modify the final callback for the inner each() to check for an Error object with a special property that indicates you're breaking out early and that it's not a real error. Then inside your conditional, pass an Error object, with that property set, to the callback.

    Example:

    // 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
    });
    

提交回复
热议问题