当我运行以下程序时
async function functionOne() {
throw new Error('Error here prints the complete stack');
await new Promise((resolve) => {
setTimeout(() => { resolve(); }, 1000);
});
}
async function functionTwo() {
await functionOne();
}
async function functionThree() {
await functionTwo();
}
functionThree()
.catch((error) => {
console.error(error);
});
我得到以下输出,该输出通过各种调用的函数打印堆栈
Error: Error here prints the complete stack
at functionOne (/home/divyanshu/programming/errorHandlingAsyncAwait/index.js:3:9)
at functionTwo (/home/divyanshu/programming/errorHandlingAsyncAwait/index.js:11:9)
at functionThree (/home/divyanshu/programming/errorHandlingAsyncAwait/index.js:15:9)
at Object.<anonymous> (/home/divyanshu/programming/errorHandlingAsyncAwait/index.js:18:1)
at Module._compile (module.js:612:30)
at Object.Module._extensions..js (module.js:623:10)
at Module.load (module.js:531:32)
at tryModuleLoad (module.js:494:12)
at Function.Module._load (module.js:486:3)
at Function.Module.runMain (module.js:653:10)
但是,在以下程序中的await调用之后引发错误时,>
async function functionOne() { await new Promise((resolve) => { setTimeout(() => { resolve(); }, 1000); }); throw new Error('Error here prints incomplete stack'); } async function functionTwo() { await functionOne(); } async function functionThree() { await functionTwo(); } functionThree() .catch((error) => { console.error(error); });
这是输出
Error: Error here prints incomplete stack at functionOne (/home/divyanshu/programming/errorHandlingAsyncAwait/index.js:7:9) at <anonymous>
我想理解为什么在第二种情况下而不在第一种情况下丢失堆栈跟踪。
当我运行以下程序时,异步函数functionOne(){抛出新错误(“错误在这里打印出完整的堆栈”);等待新的Promise((resolve)=> {setTimeout(()=> {resolve(); ...
因为在第一个代码中,直到Error
之前的所有内容都在事件循环的同一时刻。