skip to Main Content

I am new to Promises, and am running into unexpected behaviour when experimenting with the .then method. The promise below is rejected, and a value is returned by the function within the .then method, yet the promise shows {: ‘Error goes here’}.

     var myPromise = new Promise((res,rej)=>{
         rej("Error goes here")
     })
    .then(function(a){}, 
          function(error) {
        return error;
    })

//Returns "{<fulfilled>: 'Error goes here'}"

Why is this showing as ‘fulfilled’.

2

Answers


  1. The second argument of the .then() method is the same as a .catch() handler.

    In your code, the rejection will trigger that catch handler, which will return the value of the error. Because the error is considered handled, the final promise will be fullfilled with the same string that used to be the rejection reason.

    Note that a .catch() behaves the same way:

    const myPromise = new Promise((res, rej) => {
        rej("Error goes here")
    })
        .catch(function(error) {
            return error;
        })
    
    //Returns "{<fulfilled>: 'Error goes here'}"
    

    To forward the rejection from a catch handler, you have to re-throw the error:

    const myPromise = new Promise((res, rej) => {
        rej("Error goes here")
    })
        .catch(function(error) {
            throw error;
            //or `return Promise.reject(error);`
        })
    
    //Returns "{<rejected>: 'Error goes here'}"
    

    This behavior is very similar to how a normal try..catch behaves:

    function foo(){
        try{
            throw 'error goes here'
        } catch(e) {
            return e;
            //This returns the string. To keep it as exception, you have to re-throw it: `throw e;`
        }
    }
    
    console.log('Returned:', foo());
    //Returned: error goes here
    
    Login or Signup to reply.
  2. I am trying to understand what is happening with the then method.

    .then() method accepts two parameters: a callback for fulfilled and callback for rejected. You’re returning the error from the second callback (the one for rejected promises) but, it doesn’t actually cause the promise to be fulfilled. Instead, it returns a new promise that is fulfilled with the value returned by the second callback. Then, that value is the error message, so the new promise is fulfilled with that error message.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search