2017-05-12 113 views
0

我是新來承諾,我保存多個項目到MongoDB數據庫。Promise.all在第一次拒絕時沒有觸及catch塊

對於一個單一的項目,我有一個返回一個承諾的功能,即拒絕當保存到數據庫失敗,或解決,如果保存到數據庫成功:

exports.save_single_item = (itemBody, itemId) => { 
return new Promise((resolve, reject) => { 
    var new_item = new Item(itemBody); 
    new_item.save(function (err, savedItem) { 
     if (err) 
      reject('ERROR'); 
     else { 
      resolve('OK'); 
     } 

    }); 
    }); 
}; 

多個項目,我有一個函數,對於包含項目的提交數組中的每個項目,都調用上面的函數。對於這一點,我使用這個Promise.all建設:

exports.save_multiple_items = (items) => { 
var actions = items.map((item) => { module.exports.save_single_item(item, item.id) }); 
var results = Promise.all(actions); 
results.then((savedItems) => { 
    console.log('ALL OK!'); 
}).catch((error) => { 
    console.log('ERROR'); 

    }); 
}; 

的問題是,我從來沒有擊中即使每一個承諾調用save_single_item廢品results.then.catch catch塊。它直接進入then()塊並打印出'ALL OK'。我得到UnhandledPromiseRejectionWarning:未處理的承諾拒絕(拒絕ID:9):錯誤的數組中的每個項目,即使我想(?)在results.then.catch()塊捕獲它。

我在這裏錯過了什麼?

+0

試着做一個'console.log(actions)'和'console.log(savedItems)'。這會讓你知道事情出錯的地方。當事情不像你期望的那樣工作時,一些簡單的調試步驟通常會對發生的事情發光。這是一個箭頭函數是一個更高級的工具的例子,只有完全理解它是如何工作的人才能使用它。這不僅僅是一個語法快捷方式(這似乎使每個人都想立即使用它)。這是一個更高級的工具,如果使用不當,會造成錯誤。 – jfriend00

回答

2

你實際上產生的undefined的陣列,因爲這樣:

var actions = items.map((item) => { module.exports.save_single_item(item, item.id) }) 

如果你想承諾的數組,你應該去掉括號(「簡明函數體」):

var actions = items.map((item) => module.exports.save_single_item(item, item.id)) 

還是做來自塊一個明確的回報( 「塊函數體」):

var actions = items.map((item) => { return module.exports.save_single_item(item, item.id) }) 

更多的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body

相關問題