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();
순차적으로 ABC가 출력되는 걸로 보아 스택에 ABC가 순차적으로 쌓인다는 것을 알 수 있다.
callback없이 random으로 출력
const printString = (string) => {
setTimeout(
() => {
console.log(string)
},
Math.floor(Math.random() * 100) + 1
)
}
const printAll = () => {
printString("A")
printString("B")
printString("C")
}
printAll();
callback이 없어지면 random함수에 의해 무작위로 ABC가 출력되는 걸 볼 수 있다.
동기적 함수호출 방식
function waitSync(ms) {
var start = Date.now();
var now = start;
while(now - start < ms) {
now = Date.now();
}
}
function drink(person, coffee) {
console.log(person + '는 ' + coffee + '를 마십니다');
}
function orderCoffeeSync(coffee) {
console.log(coffee + '가 접수되었습니다');
waitSync(4000);
return coffee;
}
let customers = [{
name: 'Steve',
request: '카페라떼'
}, {
name: 'John',
request: '아메리카노'
}];
customers.forEach(function(customer) {
let coffee = orderCoffeeSync(customer.request);
drink(customer.name, coffee);
});
커피의 접수가 완료가 되기전까지는 다른 호출이 이루어질 수 없기 때문에 접수 후 커피를 마신 행동과 동시에 다른 커피 주문이 접수가 된다.
Async로 비동기적 호출 시
function waitAsync(callback, ms) {
setTimeout(callback, ms);
}
function drink(person, coffee) {
console.log(person + '는 ' + coffee + '를 마십니다');
}
let customers = [{
name: 'Steve',
request: '카페라떼'
}, {
name: 'John',
request: '아메리카노'
}];
function orderCoffeeAsync(menu, callback) {
console.log(menu + '가 접수되었습니다');
waitAsync(function() {
callback(menu);
}, 4000);
}
customers.forEach(function(customer) {
orderCoffeeAsync(customer.request, function(coffee){
drink(customer.name, coffee);
});
});
동시에 모든 접수가 함께 일어나고 커피를 마시는 행위가 함께 일어나게 된다.
이런 비동기적 호출 방식인 async await를 이용하면
function gotoCodestates() {
return new Promise((resolve, reject) =>{
setTimeout(() => { resolve('1. go to codestates')}, 500)
})
}
function sitAndCode(){
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('2. sit and code')}, 400)
})
}
function eatLunch() {
return new Promise((resolve, reject) => {
setTimeout(() => {resolve('3. eat lunch')}, 300)
})
}
function goToBed(){
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('4. goToBed')}, 200)
})
}
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)
}
result();
행위가 설정한 시간이 지남에 따라 일어나게 된다.
위와같은 실습으로 타이머 API를 함께 응용해볼 수도 있다.