简体   繁体   中英

rejected Promise in try-catch with/without await

The only difference between demo1 & demo2 is that demo2 add a await . How come demo1 did't catch the error and demo2 did?

// demo1
try {
    new Promise((resolve, reject) => {
        resolve()
    }).then(() => { throw new Error('haha') }) // Promise: {status: "rejected", value: Error: haha }
    console.log('irene test') // print 'irene test', execution is over.
} catch(err) { // didn't catch the error
    console.log('irene')
    console.log(err)
}

在此处输入图片说明

// demo2
try {
    await new Promise((resolve, reject) => {
        resolve()
    }).then(() => { throw new Error('haha') })
    console.log('irene test') // didn't print 'irene test'
} catch(err) { // catch the error
    console.log('irene') // print 'irene'
    console.log(err) // print err
}

在此处输入图片说明

The only difference is that this code:

try {
    new Promise((resolve, reject) => {
        resolve()
    }).then(() => { throw new Error('haha') }) // Promise: {status: "rejected", value: Error: haha }
    console.log('irene test') // print 'irene test', execution is over.
} catch(err) { // didn't catch the error
    console.log('irene')
    console.log(err)
}

is equal to this one:

const someFunction = () => { throw new Error('haha') }
try {
    new Promise((resolve, reject) => {
        resolve()
    }).then(someFunction.bind(this)) // Promise: {status: "rejected", value: Error: haha }
    console.log('irene test') // print 'irene test', execution is over.
} catch(err) { // didn't catch the error
    console.log('irene')
    console.log(err)
}

And as you can see here the someFunction has different scope than the try catch.

In demo1, control flow exits try catch block right after console.log('irene test') . So before you throw an error in Promise, it moves forward. See below.

try{
    new Promise((resolve, reject) => {
        resolve()
    }).then(() => { throw new Error('haha')})
    console.log('irene test')
} catch(err) { // catch the error
    console.log('irene') // print 'irene'
    console.log(err) // print err
}
console.log('already here')

result image You can see error is thrown after 'already here' is printed.

In demo2, as you know, promise remains in try catch block until error is thrown. (because that's what await do)

Additionally, if you want to print 'irene test' even if there is an error, it's better to use .catch .

new Promise((resolve, reject) => {
  resolve()
}).then(() => { throw new Error('haha')
}).catch(err => console.error(err))
console.log('irene test')

It successfully catches error, and also able to print 'irene test'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM