2013-05-07 32 views
9
async.map(list, function(object, callback) { 
    async.series([ 
     function(callback) { 
     console.log("1"); 

     var booltest = false; 
     // assuming some logic is performed that may or may not change booltest 
     if(booltest) { 
      // finish this current function, move on to next function in series 
     } else { 
      // stop here and just die, dont move on to the next function in the series 
     } 

     callback(null, 'one'); 
     }, 
     function(callback) { 
     console.log("2"); 
     callback(null, 'two'); 
     } 
    ], 
    function(err, done){ 
    }); 
    }); 

有沒有一些方法,例如,如果功能1,如果booltest計算結果爲真,不轉移到輸出「2」接下來的功能?有沒有辦法停止在nodejs中使用異步執行系列的下一個函數?

+1

'返回回調( '停止')'會停止你的一系列的執行和異步調用回調函數與'ERR =「stop''。 – 2013-05-07 16:00:04

+0

你能舉個例子嗎?我似乎不知道該變量(標誌)會在哪裏出現,假設booltest必須在處理列表中的元素開始處重置其自身。 – Rolando 2013-05-07 16:00:20

回答

21

,如果你與真正的回調爲你的錯誤說法,所以基本上

if (booltest) 
    callback(null, 'one'); 
else 
    callback(true); 

應工作

+0

當你說錯誤的回調,但回調(真)...這是錯誤的? – Rolando 2013-05-07 17:27:46

+0

你的第一個參數'null'實際上是你的err參數。只需將其設置爲true,即可停止執行流程。這是我的錯誤。對不起 – drinchev 2013-05-07 17:37:14

+1

我不認爲這是適當的設計。第一個參數意味着錯誤。如果回調被調用,Async恰好停止處理,但將其作爲一般方法來停止任意理由的處理對我來說似乎很奇怪。 – 2013-05-07 17:50:00

1

爲了使邏輯流程將停止,你可以只重命名error爲類似errorOrStop

var test = [1,2,3]; 

test.forEach(function(value) { 
    async.series([ 
     function(callback){ something1(i, callback) }, 
     function(callback){ something2(i, callback) } 
    ], 
    function(errorOrStop) { 
     if (errorOrStop) { 
      if (errorOrStop instanceof Error) throw errorOrStop; 
      else return; // stops async for this index of `test` 
     } 
     console.log("done!"); 
    }); 
}); 

function something1(i, callback) { 
    var stop = i<2; 
    callback(stop); 
} 

function something2(i, callback) { 
    var error = (i>2) ? new Error("poof") : null; 
    callback(error); 
} 
1

我認爲你正在尋找的功能是async.detect不會映射。

https://github.com/caolan/async#detect

檢測(ARR,迭代器,回調)

返回ARR該傳遞一個異步真理測試的第一個值。並行應用迭代器 ,這意味着返回true的第一個迭代器將觸發具有該結果的detect回調。這意味着 結果可能不是原始arr中的第一項(按照 的順序)通過測試。

示例代碼

async.detect(['file1','file2','file3'], fs.exists, function(result){ 
    // result now equals the first file in the list that exists 
}); 

你可以使用與您的booltest得到你想要的結果。

0

我傳遞一個對象來區分錯誤和正義功能。它看起來像:

function logAppStatus(status, cb){ 
    if(status == 'on'){ 
    console.log('app is on'); 
    cb(null, status); 
    } 
    else{ 
    cb({'status' : 'functionality', 'message': 'app is turned off'}) // <-- object 
    } 
} 

後來:

async.waterfall([ 
    getAppStatus, 
    logAppStatus, 
    checkStop 
], function (error) { 
    if (error) { 
     if(error.status == 'error'){ // <-- if it's an actual error 
     console.log(error.message); 
     } 
     else if(error.status == 'functionality'){ <-- if it's just functionality 
     return 
     } 

    } 
}); 
相關問題