Node는 비동기 코드를 더 깔끔하고 제어 가능하게 만드는 여러 유틸리티를 제공합니다. 오래된 callback API를 Promise로 변환하고, 작업을 취소하며, 여러 비동기 작업을 조율합니다.
promisify — callback API를 Promise로 변환
{ promisify } ;
fs ;
readFileAsync = (fs.);
data = (, );
Node는 비동기 코드를 더 깔끔하고 제어 가능하게 만드는 여러 유틸리티를 제공합니다. 오래된 callback API를 Promise로 변환하고, 작업을 취소하며, 여러 비동기 작업을 조율합니다.
{ promisify } ;
fs ;
readFileAsync = (fs.);
data = (, );
promisify는 표준 (args..., (err, result) => {}) callback 함수를 감싸 await할 수 있게 합니다. Promise 이전의 오래된 라이브러리에 유용합니다. (많은 내장 모듈이 이제 직접 promise 버전을 제공합니다. 예: fs/promises.)
const controller = new AbortController();
// pass the signal to a cancellable operation
const promise = fetch("https://api.example.com", { signal: controller.signal });
// cancel it (e.g. on timeout or user navigation)
setTimeout(() => controller.abort(), 5000); // abort after 5s
try {
await promise;
} catch (err) {
if (err.name === "AbortError") console.log("request cancelled");
}
AbortController는 진행 중인 작업(fetch, timer, stream, 많은 라이브러리)을 취소하는 표준 방식을 제공합니다. 타임아웃과, 결과가 더 이상 필요 없을 때 낭비되는 작업을 피하는 데 필수적입니다.
// run in parallel, wait for ALL (fails fast if any rejects)
const [a, b, c] = await Promise.all([getA(), getB(), getC()]);
// wait for all, get each result OR error (never short-circuits)
const results = await Promise.allSettled([getA(), getB()]);
// the first to settle (resolve OR reject) wins
const fastest = await Promise.race([fetchPrimary(), fetchBackup()]);
// the first to FULFILL (ignores rejections until one succeeds)
const first = await Promise.any([source1(), source2()]);
이 조합기들은 흔한 패턴을 표현합니다. all은 병렬 후 대기, allSettled는 실패와 무관하게 모든 결과가 필요할 때, race는 타임아웃/가장 빠른 것 우선, any는 대체 소스용입니다.
import { setTimeout as sleep } from "timers/promises";
await sleep(1000); // await a delay without wrapping in a Promise manually
이 유틸리티들은 실무 비동기 Node 코드를 더 깔끔하고 견고하게 만듭니다. promisify는 레거시 callback API를 async/await로 연결하고, AbortController는 취소와 타임아웃을 추가하며(멈추거나 낭비되는 작업 방지), Promise 조합기(all/allSettled/race/any)는 흔한 조율 패턴을 간결하고 정확하게 표현합니다.
이들을 알면 병렬성, 취소, 대체 처리를 다시 만드는 대신 우아하게 다룰 수 있습니다. 사소하지 않은 모든 비동기 애플리케이션에서 흔한 요구입니다.