节点承诺链断裂 [英] Node promise chain break

查看:46
本文介绍了节点承诺链断裂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打破承诺链,但即使在 reject('something') 之后,所有的 then(methods) 都被执行,最后catch().不应该直接执行catch跳过then(methods).

I am trying to break out of the promise chain, but even after the reject('something') all the then(methods) are getting executed and finally the catch(). Shouldn't it directly execute the catch skipping the then(methods).

method1()
.then(method2())
.then(method3())
.then(method4())
.then(method5())
.catch(errohandler())


method1(){
return new Promise(function (resolve, reject) {
    if (some condition) {
      reject(new Error("error"));
    } else {
      resolve("correct entity. all parameters present");
    }
  });
}

控制转到 if 块,因为我的条件为真,并且错误消息稍后显示在 catch 块中.然而,所有 then(methods) 都被执行了.

The control goes to the if block as my condition is true and also the error message is getting displayed in catch block later. However all the then(methods) are getting executed.

推荐答案

您没有将方法作为回调传递,而是实际调用它们并将它们的结果传递给承诺链.将其更改为此,它应该具有预期的行为.

You don't pass the methods as callbacks but you actually call them and pass their results to the promise chain. Change it to this and it should have the expected behaviour.

method1()
.then(method2)
.then(method3)
.then(method4)
.then(method5)
.catch(errohandler)

<小时>

在评论中修改场景后更新:


Update after modified scenario in comments:

如果你想用周围函数的一些参数调用 method2 那么你可以这样做:

If you want to call method2 with some parameters of the surrounding function then you could do it like so:

function myFunc(a, b){
    method1()
        .then(function() { method2(a, b); })
        // ... other chain elements
        .catch(errohandler()) 
}

这篇关于节点承诺链断裂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆