Helmut Januschka Helmut Januschka - 3 months ago 16
Node.js Question

Nodejs Promise() error swallowing

I am struggling with promises

having the following snippet:



Promise.resolve()
.then(a("OK1"))
.then(a("OK2"))
.then(a("OK3"))
.then(a("OK4"))
.then(a("OK5"))
.then(function() {
console.log("FINISH");
})
.catch(function(e) {

console.log("ERROR: " + e);
});


function a(i) {
return new Promise(function(resolve, reject) {

if(i == "OK4") {
console.log("THROW");
throw('Error'); //This does not happen
reject();
return;
}
if(i == "OK2") {
reject()
return;
}
console.log(i);
resolve();
});
}





i want to be able to reject a promise - then the next
.then
is executed ("OK3")
but i am unable to throw exceptions - i want to trigger the .catch on "OK4"

OK4 - is rejected and not outputted, but OK5 still gets executed - is there a way arround it?

this would be my expected output:

OK1
OK3
ERROR: ....

Answer

As Bergi mentioned, the parameter you are passing on each .then runs the function immediately and return a promise. The promise chain needs a reference to a function it can run at a later date.

If you want to run your function with a parameter, you can wrap it in an anonymous function so the promise chain can run the anonymous function at a later time.

a("OK1")
  .then((res)=>{
    return a("OK2")
  })
  .then((res)=>{
    return a("OK3")
  })
  .then((res)=>{
    return a("OK4")
  })
  .then((res)=>{
    return a("OK5")
  })
  .then(()=>{
    console.log("FINISH");
  })
  .catch(function(e) {
    console.log("ERROR: " + e);
  });


function a (i) {
    return new Promise(function(resolve, reject) {

        if(i == "OK4") {
           console.log("THROW");
           throw new Error(i); //This does not happen
        }
        if(i == "OK2") {
          return reject(new Error(i))
        }
        setTimeout(function () {
          console.log(i);
          resolve(i); 
        }, 100)
    });
}

It is ok to pass a function that will eventually return a promise. The function will be passed the value that the previous promise resolved with.

b(1)
  .then(b)
  .then(b)
  .then(b)
  .then((res) => {
    console.log("FINISH",res);
  })
  .catch(function (e) {
    console.log("ERROR: " + e);
  });

function b (i) {
  return new Promise(function (resolve, reject) {
    console.log(i)
    resolve(i+1)
  })
}
Comments