2013-07-22 26 views
4

我需要跳過一個async.series的函數或突破,並想知道我應該如何去做。我有一系列需要迭代的項目。我把這個列表放在一個async.each函數中。然後,數組中的每個項目都會在繼續之前通過所需的函數列表(下一個需要從中獲取信息)。但在某些情況下,我只需要通過第一個函數,然後如果不滿足條件(例如,它是我們不使用的類別),那麼回調到下一個項目的async.each循環。這裏是我的代碼示例:如何擺脫async.each循環內的異步系列 - node.js

exports.process_items = function(req, res, next){ 
var user = res.locals.user; 
var system = res.locals.system; 
var likes = JSON.parse(res.locals.likes); 
var thecat; 

//process each item 
async.each(items, function(item, callback){ 
    //with each item, run a series of functions on it... 
    thecat = item.category; 

    async.series([ 
    //Get the category based on the ID from the DB... 
    function(callback) { 
     //do stuff 
     callback(); 
    }, 

    //before running other functions, is it an approved category? 
    //if it is not an approved category, SKIP THE OTHER FUNCTIONS IN THE LIST (but how?) 
    function(callback) { 
     //do stuff 
     callback(); 
    }, 

    //some other functionality run on that item, 
    function(callback){ 
     //do stuff 
     callback(): 
    } 


    ], function(err) { 
    if (err) return next(err); 
    console.log("done with series of functions, next item in the list please"); 
}); 

//for each like callback... 
callback(); 

}, function(err){ 
    //no errors 
    }); 
} 

回答

3

將退出快捷方式放在相關函數的頂部。例如:

async.series([ 
    //Get the category based on the ID from the DB... 
    function(callback) { 
     //do stuff 
     callback(); 
    }, 

    //before running other functions, is it an approved category? 
    //if it is not an approved category, SKIP THE OTHER FUNCTIONS IN THE LIST (but how?) 
    function(callback, results) { 
     if (results[0] is not an approved category) return callback(); 
     //do stuff 
     callback(); 
    }, 
+2

但是,這隻會退出該功能嗎?或者會要求它將回調結束迴歸系列?我想結束系列而不運行系列中的所有其他功能,並再次返回到async.each。 –

+0

它不會結束這個系列,但它會阻止任何工作的發生並將控制權重新發送到async.each。如果結果未得到批准,您需要在不想運行的任何函數的開頭部署這些函數。我也只是注意到你需要在console.log行之後調用回調函數。隨着所有不同的回調函數浮動,很容易被絆倒。 – Allan

+0

它的工作,感謝艾倫! –