gpt4 book ai didi

javascript - NodeJs 错误处理 try catch block 中的 promise 错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:31:12 26 4
gpt4 key购买 nike

我应该如何处理 catch block 中从 Promise 抛出的错误?

例如,

try {

// some other functions/code that can also throw error

var promise = // a service that returns new Promise() object

promise.then(function(data) {
//some business logic
}, function(err) {
throw new Error(err); // never gets caught in catch block
});
} catch(error) {
// do something with error
console.log(error);
}

1) 是否可以处理从 Promise 抛出的 try catch block 中的错误?

2)是否有更好的方法来处理常见错误?

最佳答案

Promise 异步工作,使它们在此处的 catch block 的范围之外执行。这就是为什么他们有自己的 catch 版本 -

promise
.then(function(data) {
//some business logic
return anotherPromise;
})
.then(function(data) {
//some other business logic
})
// this keeps chaining as long as needed
.catch(function(err) {
// You will get any thrown errors by any of the
// chained 'then's here.
// Deal with them here!
});

这是推荐的方式。

关于javascript - NodeJs 错误处理 try catch block 中的 promise 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37562209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com