Search code examples
javascriptpromise

why promise returns an unexpected output for nested promises?


I have code below and based on MDN document, I know how result and state will be specified for a promise, resulted from a handler:

returns a value: p gets fulfilled with the returned value as its value.

doesn't return anything: p gets fulfilled with undefined as its value.

throws an error: p gets rejected with the thrown error as its value.

returns an already fulfilled promise: p gets fulfilled with that promise's value as its value.

returns an already rejected promise: p gets rejected with that promise's > value as its value.

returns another pending promise: p is pending and becomes fulfilled/rejected with that promise's value as its value immediately after that promise becomes fulfilled/rejected.

so why the state for my promise is fullfilled?

code:

const test = Promise.reject(new Promise((resolve, reject) => {
throw new Error("error")
}))

const test2 = test.catch((result) => {
result.catch(() => {
    throw new Error("error2");
})
})

console.log(test2);

//result in console:
//[[Prototype]]: Promise
//[[PromiseState]]: "fulfilled"
//[[PromiseResult]]: undefined

Solution

  • You forgot to return the inner promise:

    const test = Promise.reject(new Promise((resolve, reject) => {
    throw new Error("error")
    }))
    
    const test2 = test.catch((result) => {
      return result.catch(() => {
        throw new Error("error2");
    })
    })
    
    console.log(test2);
    enter image description here