Chapter1. 고차함수 리뷰
Chapter2. 비동기
Chapter3. Node.js
비동기 함수 전달 패턴1: callback 패턴
let request = 'caffelatte'; orderCoffeeAsync(request, function(response) { // response -> 주문한 커피 결과 drink(response); });
비동기 함수 전달 패턴2: 이벤트 등록 패턴
let request = 'caffelatte'; orderCoffeeAsync(request).onready = function(response) { // response -> 주문한 커피 결과 drink(response); };
비동기 함수의 순서를 제어하고 싶을 때 사용
ex)
const printString = (string, callback) => {
setTimeout(() => {
console.log(string);
callback()
},
Math.floor(Math.random() * 100) + 1
)
}
const printAll = () => {
printString("A", () => {
printString("B", () => {
printString("C", () => {})
})
})
}
printAll();
단점 : 콜백헬 발생. 가독성 떨어짐
const printString = (string) => {
return new Promise((resolve, reject) => {
setTimeout(
() => {
console.log(string);
resolve();
},
Math.floor(Math.random() * 100) + 1
)
})
}
const printAll = () => {
printString("A")
.then(() => {
return printString("B");
})
.then(() => {
return printString("C");
})
}
printAll();
Promise와 동일하게 작동하나 겉으로 보이는 모습은 다름.
promise보다 가독성이 좋다.
setTimeout(callback, millisecond)
: 일정 시간 후에 함수를 실행setTimeout(function () {
console.log('1초 후 실행');
}, 1000);
// 123
clearTimeout(timerId)
: setTimeout 타이머를 종료const timer = setTimeout(function () {
console.log('10초 후 실행');
}, 10000);
clearTimeout(timer);
// setTimeout이 종료됨
setInterval(callback, millisecond)
: 일정 시간의 간격을 가지고 함수를 반복적으로 실행setInterval(function () {
console.log('1초마다 실행');
}, 1000);
// 345
clearInterval(timerId)
: setInterval 타이머를 종료const timer = setInterval(function () {
console.log('1초마다 실행');
}, 1000);
clearInterval(timer);
// setInterval이 종료됨.
Node.js : "비동기 이벤트 기반 JavaScript 런타임"
const fs = require('fs'); // 파일 시스템 모듈을 불러옵니다
const dns = require('dns'); // DNS 모듈을 불러옵니다
공식적으로 제공하는 빌트인 모듈(built-in module)이 아닌 모든 외부 모듈
fs.readFile(path[, options], callback)
fs.readFile
path \<string> | \<Buffer> | \<URL> | \<integer>
path
에는 파일 이름을 전달인자로 받음. string
)의 타입을 받음.fs.readFile('/etc/passwd', ..., ...)
[코드] '/etc/passwd' 파일을 불러오는 예제
options \<Object> | \<string>
options
는 넣을 수도 있고, 넣지 않을 수도 있다. // /etc/passwd 파일을 'utf8'을 사용하여 읽습니다.
fs.readFile('/etc/passwd', 'utf8', ...);
[코드] 두 번째 전달인자 options에 문자열을 전달한 경우
callback \<Function>
err
는 null
이 되며data
에 문자열이나 Buffer
라는 객체가 전달됨