Node promise chain break

2019-06-14 13:47发布

问题:

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

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.

回答1:

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:

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