如果有一个包含异步函数的 promise ,并且如果异步函数中发生错误,则 promise 不会捕获,而是会抛出错误并使应用程序崩溃,这是我不明白的。
显然我想处理这个错误,你知道为什么 Promise 会这样吗?有什么办法可以解决它?
谢谢
// this promise will have an error since param is not defined,
// and the promise won't be caught
function randomPromise(param) {
return new Promise((resolve, reject) => {
setTimeout(() => {
param[0] = 11;
}, 2000);
});
}
randomPromise()
.then(() => {
console.log('nothing');
})
.catch((e) => {
console.log('with set timeout or any async function in the promise, the error caused by \'param[0] = 11;\' wont bring the control here into the catch block just throws an error and crashes the application');
console.log(e);
});
// this promise will have an error since param is not defined
// but the promise will be caught
function randomPromiseGoesToCatchBlock(param) {
return new Promise((resolve, reject) => {
param[0] = 11;
});
}
randomPromiseGoesToCatchBlock()
.then(() => {
console.log('nothing');
})
.catch((e) => {
console.log('without the setTimeout function or any async function the error caused by \'param[0] = 11;\' brings the control here into the catch block');
console.log(e);
});
最佳答案
在 Promise
构造函数中抛出的错误以及异步发生的错误需要显式 try
/catch
ed,以便调用reject
,从而将Promise控制流转移到Promise的catch
中。例如:
// this promise will have an error since param is not defined, and the promise wont be catched
function randomPromise(param) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
param[0] = 11;
} catch(e) {
reject(e);
}
}, 2000);
});
}
randomPromise()
.catch((e) => {
console.log(e.message);
});
否则,resolve
和 reject
都不会被调用,并且错误是异步的,因此创建 Promise 的线程已经结束,因此解释器不会'我不知道抛出的错误应该拒绝该 Promise,而无需您明确告诉它。
相反,在 Promise
构造函数内同步抛出的错误将自动导致构造的 Promise 立即拒绝。
关于javascript - Promise 中的异步函数会抛出错误并且不会拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54611416/