在 JavaScript 中处理异步函数时。我发现了这个问题。
函数需要执行一些异步任务,但是该任务对函数结果没有影响。因此函数返回其结果,一段时间后,异步函数会抛出异常,但是由于控制权已经返回,因此异常不会被处理。
注意:不要更改notify
我是故意抛出这样的错误,只需要处理这个异常
代码如下:
function notify() { //To send notification
setTimeout( function() { //Just to simulate an asynchronous function
throw "Exception occurred"; //An exception from async function
},2000);
return "Notified";
}
try {
let result = notify();
console.log(result); //Notified
}
catch (error) { //Never comes to catch block.
console.log(error);
}
如何捕获这个异常。 尝试使用 Promise,但是它不能用 Promise 解决,因为即使使用 Promise,当调用函数收到响应时,流或函数也会从内存中删除。
使用 Promise 的代码
function notify() { //To send notification
return new Promise ( (resolve, reject) => {
setTimeout( function() { //Just to simulate an asynchronous function
throw "Exception occurred"; //An exception from async function
},2000);
resolve("Notified");
});
}
notify()
.then( result => {
console.log(result); //Notified
})
.catch( error => { //Never comes to catch block
console.log(error);
});
如何捕获 JavaScript 编程中的异常?
最佳答案
我会将 setTimeout 包装在一个 promise 中:
const delay = ms => new Promise(res => setTimeout(res, ms));
这允许您将 notify
编写为:
async function notify() {
await delay(2000);
throw new Error();
}
notify().then(/*...*/).catch(/*...*/);
这里的技巧是 throw
位于异步函数内部,而不是像您的情况那样位于回调内部。
关于javascript - JavaScript 中函数返回结果后如何处理函数中的意外错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51921124/