Async와 Await
Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 16번째.
.then 호출을 연결한 코드는 단계를 생각하는 방식인 읽고, 파싱한 다음, 저장하는 순서와는 다르게 읽힙니다.
async 함수 안에서 await는 프라미스가 완료될 때까지 실행을 멈추고 그 값을 반환합니다. 프라미스가 실패하면 그 지점에서 예외가 발생하므로 try와 catch로 처리할 수 있습니다. 모듈에서는 최상위 수준에서도 await를 사용할 수 있습니다.
import { readFile } from 'node:fs/promises';
const loadConfig = async () => {
try {
return JSON.parse(await readFile('config.json', 'utf8'));
} catch {
return {};
}
};
const config = await loadConfig();
console.log(config.port ?? 3000);async 함수는 항상 프라미스를 반환하므로 호출하는 쪽에서도 이를 기다려야 합니다. await를 빠뜨리면 값 대신 프라미스 자체인 Promise { <pending> }을 받게 됩니다.
챌린지
쉬움store.js는 이제node:fs/promises를 사용해 읽고 씁니다. 모든 명령이 이전처럼 작동하도록 빠진await를 추가하세요.- 이제
async인store.add와store.remove를notes.js에서 기다립니다.
먼저 node notes.js list를 실행해 오류를 읽고, 작동하면 add와 done 1을 실행하세요.
직접 해보기
import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';
const file = 'notes.json';
// readFile과 writeFile은 이제 프로미스를 반환합니다. await으로 각각의 결과를 기다리세요.
const load = async () => {
if (!existsSync(file)) {
return [];
}
try {
return JSON.parse(readFile(file, 'utf8'));
} catch (err) {
console.error(`notes.json is damaged: ${err.message}`);
process.exit(1);
}
};
const store = {
notes: load(),
async save() {
writeFile(file, JSON.stringify(this.notes, null, 2));
},
async add(text) {
this.notes.push(text);
this.save();
return this.notes.length;
},
async remove(n) {
const [text] = this.notes.splice(n - 1, 1);
this.save();
return text;
},
};
export default store;
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.