【发布时间】:2019-07-03 19:37:09
【问题描述】:
如果有一个带有异步函数的 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);
});
【问题讨论】:
标签: javascript asynchronous error-handling promise catch-block