如果在循环内抛出错误,则破坏 promise map

Break promise map if throw error inside the loop

我正在使用 Hapi Js 和 Sequelize 对我的 API 做一些事情,在这种情况下,我需要先检查所有内容,然后再进行下一步。

这是我的代码

return promise.map(array, function (values) {
    models.Goods.find({
        where: {
            id: values.id
        }
    }).then(function (res) {
        if (!res || res.length === 0) {
            throw new Error("Item not found");
        }
    });

}).then(function (res) {
    //do something after check
    //next step
}).catch(function(error) {
    console.log(error.message);
});

我需要在进行下一步之前检查该 ID 是否在我的数据库中,但是在此代码中如果有任何错误 throw new Error("Item not found"); 永远不会转到 catch function 所以我尝试做一些事情来获得错误功能。我更改了 promise.map 中的代码,我在 models.Goodsconsole.log 中放置了 catch 函数,错误出现了,但 promise.map 仍然是 运行 然后继续到 //next step 部分,不停下来。

如果models.Goods

有错误请帮我破解promise.map

谢谢

当没有找到用户时,查询本身就成功了,所以会触发成功回调。但由于没有任何内容与您的查询匹配,因此返回 null。这就是为什么它首先不触发错误的原因。至于第二部分。

您无法捕获使用 promise 的异步回调函数中抛出的错误,因为它的上下文将会丢失。

使用承诺,正确的解决方案是拒绝包装承诺。

Promise.reject(new Error('fail')).then(function(error) {
  // not called
}, function(error) {
  console.log(error); // Stacktrace
});

我想你只是忘了return模型,这个

return promise.map(array, function (values) {
  models.Goods.find({
    where: {

应该是:

return promise.map(array, function (values) {
  return models.Goods.find({
    where: {

如果使用箭头 functions,您可以省略 return 关键字。
这里有一个例子,我也放了一些object destructuring.

return promise.map(array, ({id}) => 
    models.Goods.find({
        where: {id}
    }).then(res => {
        if (!res || res.length === 0) {
            throw new Error("Item not found");
        }
    }) // can't have ; here now
).then(res => {
    // do something after check
    // next step
}).catch(error => {
    console.log(error.message);
});