Promise
Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 15번째.
콜백 안에 콜백이 있으면 따라가기 어려워지고, 각 콜백에서 매번 err를 확인해야 합니다.
node:fs/promises는 대신 프로미스를 반환합니다. 프로미스는 나중에 도착하는 결과를 나타내는 객체입니다. .then(fn)은 결과가 있으면 실행되고, .catch(fn)은 그 전에 어느 단계에서든 실패하면 실행되며, .finally(fn)은 어느 쪽이든 실행됩니다.
import { readFile } from 'node:fs/promises';
readFile('poem.txt', 'utf8')
.then((text) => console.log(text.length + ' characters'))
.catch(() => console.log('No poem today'))
.finally(() => console.log('Bye'));.then 안에서 발생한 오류도 .catch로 전달되므로, 하나의 처리기로 읽기와 파싱을 모두 처리할 수 있습니다. .catch가 없는 상태에서 실패하는 프로미스는 프로그램을 충돌시킵니다.
챌린지
쉬움node:fs/promises의readFile과.then을 사용해count.js를 다시 작성하세요.- 이제 파일이 없으면
.catch에서No notes yet을 출력합니다. .finally에서 출력되는Done은 여전히 마지막에 나옵니다.
node count.js를 실행한 다음 node count.js nothere.json을 실행하세요.
직접 해보기
import fs from 'node:fs';
const file = process.argv[2] ?? 'notes.json';
console.log('Reading...');
fs.readFile(file, 'utf8', (err, text) => {
if (err) {
console.log(`Cannot read ${file}`);
} else {
console.log(`${JSON.parse(text).length} notes`);
}
console.log('Done');
});