동기(synchronous) : 동시에 일어난다는 뜻으로 시작 시점과 완료 시점이 같은 상황
비동기(asynchronous) : 동시에 일어나지 않는다는 뜻으로 시작 시점과 완료 시점이 같지 않은 상황
Node.js는 non-blocking하고 비동기적으로 작동하는 런타임
동기 호출
callback in action
❗️함수 실행을 연결하는 것이 아니라 함수자체를 연결해야 한다.
blocking vs. non-blocking
blocking : 요청에 대한 결과가 동시에 발생 ex)전화 : 하던 일을 멈추고 받아야 함
non-blocking : 요청에 대한 결과가 동시에 발생하지 않음 ex) 문자 : 확인 후, 나중에 답장 가능
비동기 함수 전달 패턴 1 : callback 패턴
비동기 함수 전달 패턴 2 : 이벤트 등록 패턴
비동기의 주요 사례
Async JavaScript
Node.js : As an asynchronous event-driven JavaScript runtime
Callback
const getDataFromFile = function (filePath, callback) {
return fs.readFile(filePath, { encoding: 'utf8', flag: 'r' }, (err, data) => {
callback(err, data === undefined ? null : data);
});
};
Promise
task 종료 .then task 실행
.catch로 에러 handling
return을 사용해 promise 헬 방지
Promise Chaining
const getDataFromFilePromise = (filePath) => {
return new Promise((resolve, reject) => {
const options = { encoding: "utf8", flag: "r" };
fs.readFile(filePath, options, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
async await
await을 통해 가독성 Up
const readAllUsersAsyncAwait = async () => {
const usersStr = [
await getDataFromFilePromise(user1Path),
await getDataFromFilePromise(user2Path),
];
return usersStr.map(JSON.parse);
};