简体   繁体   English

Promise.All在第一次拒绝时没有碰到捕获块

[英]Promise.all not hitting catch block upon first rejection

I'm new to promises and I'm saving multiple items to MongoDB database. 我是诺言新手,正在将多个项目保存到MongoDB数据库中。

For a single item, I have a function that returns a promise, which rejects when the save to the database failed, or resolves if the save to the database succeeded: 对于单个项目,我有一个返回promise的函数,该函数在保存到数据库失败时拒绝,或者解决保存到数据库是否成功的情况:

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');
        }

    });
  });
};

For multiple items, I have a function that, for each item in the submitted array containing items, calls the function above. 对于多个项目,我有一个函数,对于提交的包含项目的数组中的每个项目,都调用上述函数。 For that, I'm using this Promise.all construction: 为此,我正在使用此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');

  });
};

The problem is, I'm never hitting the catch block on results.then.catch even though every promise call to save_single_item rejects. 问题是,即使对save_single_item的每个promise调用都被拒绝,我也永远不会在result.then.catch上碰到catch块。 It goes straight into the then() block and prints out 'ALL OK'. 它直接进入then()块并打印出“ ALL OK”。

I'm getting UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 9): ERROR for every item in the array, even though I'm supposedly(?) catching it at the results.then.catch() block. 我正在得到UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:9):数组中每个项目的错误,即使我是想以(?)在result.then.catch()块中捕获它。

What am I missing here? 我在这里想念什么?

You are actually generating an array of undefined , because of this: 由于这个原因,您实际上正在生成一个undefined数组:

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

If you want an array of promises, you should remove the brackets ("concise function body"): 如果您需要一个诺言数组,则应删除方括号(“简洁函数体”):

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

Or do an explicit return from the block ("block function body"): 或从该块(“块函数主体”)进行显式返回:

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

More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body 此处提供更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM