我有一个调用 promise 的函数。无论成功还是失败,我都想返回一些超出 promise 返回的数据。
我认为这可能有效:
function foo() {
const extra = 'bar'
return thepromise().then((res) => {
return {
result: res,
data: extra
}
}, (err) => {
// this will not happen if an error is thrown in the called promise
return {
result: res,
data: extra
}
})
}
foo().then((res) => { }, (err) => { // error result ends up here })
但是这不起作用。如果在 thepromise
中抛出错误,它不会调用 catch block ,而是调用 foo()
的 catch block 。
处理这个问题的正确方法是什么?我成功使用了 try/catch block ,但我不确定这是最好的方法:
function foo() {
const extra = 'bar'
return new Promise((resolve, reject) => {
try {
return thepromise(p)
} catch (e) {
reject(e)
}
})
.then(function(res) {
return {
result: res,
data: extra,
status: 'success'
}
}, function(err) {
return {
result: err,
data: extra
status: 'error'
}
})
}
最佳答案
任何旨在返回 Promise 的函数都不应该抛出任何类型的异常或错误。
如果确实如此,则应将其视为有错误。
要修复有错误的方法,不要抛出异常,而是拒绝返回的 Promise。
<小时/>有时您无法修复潜在的错误,例如当您使用其他人的 API 时。如果是这种情况,首先要做的也是最重要的事情就是向原作者报告该错误,以便解决根本问题。
报告问题后,您可以将有问题的方法包装在一个简单的实用程序中来修复问题:
function fixBrokenPromise(promise/*, args...*/) {
var args = Array.prototype.slice.call(arguments, 1),
ret;
try {
ret = promise.apply(null, args);
} catch (ex) {
ret = Promise.reject(ex);
}
return ret;
}
这可以称为:
fixBrokenPromise(thepromise/*, args you want to pass to thepromise */)
.then(...resolve...,
...reject...);
关于javascript - 将 Promise 包装在 try/catch block 中是正确的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38810282/