繁体   English   中英

在带/不带等待的 try-catch 中拒绝承诺

[英]rejected Promise in try-catch with/without await

demo1 和 demo2 之间的唯一区别是 demo2 添加了await 为什么 demo1 没有捕捉到错误而 demo2 却捕捉到了错误?

// 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
}

在此处输入图片说明

唯一的区别是这段代码:

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

等于这个:

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

正如你在这里看到的, someFunction作用域与 try catch 的作用域不同。

在 demo1 中,控制流在console.log('irene test')之后立即退出 try catch 块。 所以在你在 Promise 中抛出错误之前,它会继续前进。 见下文。

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')

结果图像您可以看到在打印 'already here' 后抛出错误。

在 demo2 中,如您所知,promise 会保留在 try catch 块中,直到抛出错误为止。 (因为这就是 await 所做的)

此外,如果即使出现错误也想打印 'irene test',最好使用.catch

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

它成功捕获错误,并且还能够打印“irene test”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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