【发布时间】:2021-09-24 23:13:22
【问题描述】:
我有这个复制品:https://codesandbox.io/s/jolly-bogdan-k6ii4?file=/src/index.ts
代码:
const wait = (timeoutMs: number) => {
let timeoutHandle: number | undefined;
const promise = new Promise((_resolve, reject) => {
timeoutHandle = setTimeout(() => {
reject(`wait timed out after ${timeoutMs} ms`);
}, timeoutMs);
});
return {
promise,
cancel: (): void => clearTimeout(timeoutHandle)
};
};
const waitBy = (timeoutMs: number) => {
const res = wait(timeoutMs);
return res;
};
const main = async () => {
try {
const { promise, cancel } = waitBy(3000);
} catch (error) {
console.log("failed on timeout");
}
// try {
// await promise;
// } catch (error) {
// console.log("timed out");
// }
};
main();
当它在 Node.js 中运行时,reject 将在 3 秒后抛出,并以“unhandledRejection 错误”炸毁整个过程 - catch 这个错误在哪里可以避免 unhandledRejection 错误,但允许它传播到main 函数内的catch?
【问题讨论】: