【问题标题】:Break promise map if throw error inside the loop如果在循环内抛出错误,则打破承诺映射
【发布时间】:2018-01-19 14:52:32
【问题描述】:

我正在使用 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 中的代码,我将catch 函数放入models.Goodsconsole.log 错误中,错误显示但promise.map 仍在运行并转到//next step 部分而不是停止。

如果models.Goods有错误,请帮助我如何破解promise.map

谢谢

【问题讨论】:

标签: javascript node.js promise sequelize.js hapijs


【解决方案1】:

我想你只是忘记归还模型,这个

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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-03-12
      • 2017-07-26
      • 2016-04-17
      • 2018-09-29
      • 1970-01-01
      • 2018-02-19
      • 2021-02-28
      • 1970-01-01
      • 2016-02-26
      相关资源
      最近更新 更多