2014-05-10 195 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. 
    });