비동기 함수(Promise, async/await)를 사용할 때 에러를 처리하는 방법
const resolved = (arg, delay = 100) =>
new Promise((resolve) =>
setTimeout(() => {
console.log("resolved", { arg });
resolve(arg);
}, delay),
);
const rejected = (arg, delay = 100) =>
new Promise((_, rejected) =>
setTimeout(() => {
console.log("rejected", { arg });
rejected(arg);
}, delay),
);
const asyncFn = async () => {
const fn1 = rejected(1).catch((e) => {
console.error("catch chaining 1", { e });
});
console.log("fn1", fn1);
const fn2 = rejected(2);
console.log("fn2", fn2);
const fn3 = rejected(3).catch((e) => {
console.error("catch chaining 3", { e });
});
console.log("fn3", fn3);
};
asyncFn()
.then(() => console.log("최종 then"))
.catch(() => console.log("최종 catch"));
Promise<fulfilled>
되어 then이 실행된다. Uncaught
에러로 평가되어 에러를 처리할 수 없다. Uncaught
에러로 전달되어 에러를 처리할 수 없다. const asyncFn = async () => {
const fn1 = await rejected(1).catch((e) => { // await 로 즉시 평가
console.error("catch chaining 1", { e });
throw e;
});
console.log("fn1", fn1);
const fn2 = rejected(2);
console.log("fn2", { fn2 });
const fn3 = rejected(3).catch((e) => {
console.error("catch chaining 3", { e });
throw e;
});
console.log("fn3", { fn3 });
};
const asyncFn = async () => {
try {
const fn1 = rejected(1).catch((e) => {
console.error("catch chaining 1", { e });
throw e; // catch구문에서 throw하더라도 await로 즉시평가되지 않았기 때문에 try-catch구문에서는 잡을 수 없음.
});
console.log("fn1", fn1);
const fn2 = rejected(2);
console.log("fn2", { fn2 });
const fn3 = rejected(3).catch((e) => {
console.error("catch chaining 3", { e });
throw e;
});
console.log("fn3", { fn3 });
} catch (e) {
console.error("try-catch", { e });
throw e;
}
};
Promise<fulfilled>
상태로 실행컨텍스트가 종료된다.Uncaught
에러로 종료된다. const asyncFn = async () => {
try {
const fn1 = rejected(1).catch((e) => {
console.error("catch chaining 1", { e });
});
console.log("fn1", await fn1); // await 구문으로 try-catch 내에서 평가하지만 throw X
const fn2 = rejected(2);
console.log("fn2", fn2);
const fn3 = rejected(3).catch((e) => {
console.error("catch chaining 3", { e });
throw e;
});
console.log("fn3", await fn3); // await 구문으로 try-catch 내에서 평가 및 throw
} catch (e) {
console.error("try-catch", { e });
throw e;
}
};
Promise<fulfilled>
된다.Promise<fulfilled>
된다.