2017-05-12 115 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

相关问题