function B(){
console,.log('called at the back!');
}
function A(callback){
callback(); //callback === B
}
A(B)
[1,2,3].map(function(element, index){
return element * element;
});
document.querySelector('#btn').addEventListener('click', function(e){
console.log('button clicked');
})
헷갈리지 말기!
function handleClick(){
console.log('button clicked');
}
//바른 방법
document.querySelector("#btn").onclick = handleClick;
document.querySelector("#btn").onclick = function(){
handleClick();
}
document.querySelector("#btn").onclick = handlleClick.bind();
//옳지 않은 방법
document.querySelector("#btn").onclick = handlerClick();
// 함수 실행을 연결하는 것이 아님. 함수 자체를 연결하는것
전화
: 하던일을 멈추고 받아야함 (blocking) => 요청에 대한 결과가 동시에 일어남 (synchronous)
문자
: 확인 후, 나중에 답장할 수 있음 (non-blocking) => 요청에 대한 결과가 동시에 일어나지 않음(asynchronous)
let request = 'caffelatte';
orderCoffeeAsync(request, function(response){
//response -> 주문한 커피 결과
drink(response)
}
let request = 'caffelatte';
orderCoffeeAsync(request).onready = function(response){
//response -> 주문한 커피 결과
drink(response)
}
DOM Element의 이벤트 핸들러
타이머
서버에 자원 요청 및 응답
sync 효율적이라고 볼 수 있음
순서를 제어하고 싶은 경우에는 어떻게?
const printString = (string) =>{
setTimeout(
() => {
console.log(string)
},
Math.floor(Math.random() * 100) + 1
)
}
const printAll =() =>{
printString('A')
printString('B')
printString('C')
}
printAll() // what do you can expect?
이 함수는 순서가 랜덤으로 나옴
그래서 callback이 필요함
const printString = (string, callback) =>{
setTimeout(
() => {
console.log(string)
callback()
},
Math.floor(Math.random() * 100) + 1
)
}
const printAll = () => {
printString('A',()=> {
printString('B', () => {
printString('C', () => {
})
})
})
}
printAll() // what do you can expect?
A
B
C
순서대로 나옴
const somethingGonnaHappen = callback => {
waitingUntilSomthingHappen()
if(isSomethingGood){
callback(null, something)
}
if(isSomethingBad){
callback(something, null)
}
}
somethingGonnaHappen((err,data) => {
if(err){
console.log('ERR');
return
}
return data;
})
callback 함수 문제점:
callback HELL!!
가독성이 매우 떨어짐
callback 함수 단점을 보완하기 위해서 Promise사용한다고 보면 될듯
How to deal with callback chain (callback HELL)
promise
: 하나의 class라고 생각하면 될듯
new Promise()를 통해서 인스턴스가 만들어지게 되는데
resolve() = Go to Next Action
reject() = Handle Error
를 통해서 다음 액션으로 넘어가거나 에러를 핸들링 할 수 있음
callback -> promise
동작은 동일하지만, 가독성이 좋아짐 + error 처리할때 마지막에 .catch()로 한번에 할 수 있음
//callback 함수
const printString = (string, callback) =>{
setTimeout(
() => {
console.log(string)
callback()
},
Math.floor(Math.random() * 100) + 1
)
}
const printAll = () => {
printString('A',()=> {
printString('B', () => {
printString('C', () => {
})
})
})
}
printAll() // what do you can expect?
// promise 함수
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')
})
}
promise도 promise HELL이 있음
return 처리를 잘 해주면 promise HELL을 벗어날 수 있음..
await을 통해서 비동기 함수를 마치 동기적인 함수처럼 쓸 수 있음
async 함수라는 것을 꼭 표시해주어야 함!!
일정 시간 후에 함수를 실행
매개변수(parameter): 실행할 콜백 함수, 콜백 함수 실행 전 기다려야 할 시간 (밀리초)
return 값: 임의의 타이머 ID
setTimeout(function () {
console.log('1초 후 실행');
}, 1000);
// 123
setTimeout 타이머를 종료
매개변수(parameter): 타이머 ID
return 값: 없음
const timer = setTimeout(function () {
console.log('10초 후 실행');
}, 10000);
clearTimeout(timer);
// setTimeout이 종료됨.
일정 시간의 간격을 가지고 함수를 반복적으로 실행
매개변수(parameter): 실행할 콜백 함수, 반복적으로 함수를 실행시키기 위한 시간 간격 (밀리초)
return 값: 임의의 타이머 ID
setInterval(function () {
console.log('1초마다 실행');
}, 1000);
// 345
setInterval 타이머를 종료
매개변수: 타이머 ID
return 값: 없음
const timer = setInterval(function () {
console.log('1초마다 실행');
}, 1000);
clearInterval(timer);
// setInterval이 종료됨.
+추가