다른 함수의 매개변수로 함수를 전달하고, 어떠한 이벤트가 발생한 후 매개변수로 전달한 함수가 다시 호출되는 것
[1, 2, 3].map(function(element, index){
return element * element;
})
document.querySelector('#btn').addEventListener('click', function(e){console.log('button clicked')
})
:요청에 대한 결과가 동시에 일어나지 않는다
let request = 'caffelatte'
orderCoffeeAsync(request, function(response){
//response -> 주문한 커피 결과
drink(response)
})
let request = 'caffelatte'
orderCoffeeAsync(request).onready = function(response){
//response => 주문한 커피 결과
drink(response)
}
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()
function gotoCodestates(){
return new Promise((resolve, reject) => {
setTimeout(() => {resolve('1. go to codestates')}, 100)
})
}
function sitAndCode(){
return new Promise((resolve, reject) => {
setTimeout(() => {resolve('2. sit and code')}, 100)
})
}
function eatLunch(){
return new Promise((resolve, reject) => {
setTimeout(() => {resolve('3. eat lunch')}, 100)
})
}
function goToBed(){
return new Promise((resolve, reject) => {
setTimeout(() => {resolve('4. goToBed')}, 100)
})
}
const result = async () =>{
const one = await gotoCodestates();
console.log(one)
const two = await sitAndCode();
console.log(two)
const three = await eatLunch();
console.log(three)
const four = await gotoBed();
console.log(four)
(path, [options], callback)
:로컬에 존재하는 파일을 읽어오는 메소드
비동기적으로 파일 내용 전체를 읽고 이 메소드를 실행할 때는 인자 3개를 넘길 수 있음
fs.readFile('/etc/passwd', ..., ...)```
options는 넣을 수도 있고, 넣지 않을 수도 있고 객체 형태 또는 문자열로 넘길 수 있음
let options = {
encoding: 'utf8', // UTF-8이라는 인코딩 방식으로 엽니다
flag: 'r' // 읽기 위해 엽니다
}
// /etc/passed 파일을 옵션을 사용하여 읽습니다.
fs.readFile('/etc/passwd', options, ...) ```
#### callback \<Function>
콜백 함수를 전달하며 파일을 읽고 난 후에 비동기적으로 실행되는 함수
두가지 파라미터가 존재하는데
1. 에러가 발생하지 않으면 err는 null이 되며,
2. data(파일의 내용)에 문자열이나 Buffer라는 객체가 전달됨
```js
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) {
throw err; // 에러를 던집니다.
}
console.log(data);
}); ```