2014-09-06 95 views
1

我有一個數組需要追加到數據庫中,條件是,元素必須一個接一個地追加以使其工作,以下是我的代碼,似乎不會順序執行命令,我的代碼有什麼問題:謝謝。在Promose/bluebird中按順序執行命令

var B = require('bluebird') 
var appends = [] 

recs.forEach(function (item) { 
    appends.push(dao.append_rec_cartAsync(item)) 
}) 

B.all(appends).then(function() { 
    console.log('all done') 
})   

回答

0

當你調用dao.append_rec_cartAsync(item)執行異步操作。一旦開始,你無法對其運行做任何事情。另請注意,Promise.all不是按順序執行,而是相互平行。

var B = require('bluebird'); 
B.each(recs, function(item){ // note we use B.each and not forEach here 
    // we return the promise so it knows it's done 
    return dao.append_recs_cartAsync(item); 
}).then(function(){ 
    console.log("all done!") 
}); 

或簡稱:B.each(recs, dao.append_recs_cartAsync)

+0

作品,什麼是每減少之間的區別? – AngeloC 2014-09-07 06:24:58

+0

@AngeloC他們非常相似,他們都保證秩序,但「減少」更一般。 'reduce'爲每個下一個函數提供前一個計算的返回值,其中'each'給每個下一個函數提供數組元素本身。 – 2014-09-07 07:34:50

+0

該文檔說:具有簽名的reducer函數(total,current,index,arrayLength),無法理解'total – AngeloC 2014-09-07 10:22:55