2014-05-10 194 views
2

我有一个名为recipesArray的对象数组数组。突破javascript嵌套的async.each循环,但继续主循环

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

回答

6

一种方式是修改针对每个内()最终回调用来检查一个特殊的属性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 
}); 
+0

这似乎是它的工作,感谢@mscdex。 – Joel

+0

虽然我仍然想知道是否有更好的办法比伪造一个错误。 – Joel

+0

当前没有使用'async'模块,当我需要使用'async'模块方法提前打破时,我实际上使用了这种模式。 – mscdex

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