7시간 좀 못 잤음에도 월드컵과 함께 눈을 뜰 수 있었다.
따뜻한 차 마시니 역시 효과는 굉장했다.
금요일이라는 생각에 더 괜찮았다.
동기: A작업이 모두 진행될 때 까지 B작업은 대기
비동기: 요청을 보냈을 때 응답과 상관없이 다음 동작 수행 가능. A작업 시작하면 B작업 시작. A작업은 결과값 나오는대로 출력
-비동기 예시
console.log("1st");
setTimeout(() => {
console.log("2nd");
}, 0)
console.log("3rd")
// 1 / null / 3 / 2
// setTimeout은 비동기적 api라 실행하면서 밑으로 내려가고 2는 나오는 대로 출력하니까
const printString = (string, callback) => {
setTimeout(() => {
console.log(string);
callback();
}, Math.floor(Math.random() * 100) + 1);
};
const printAll = () => {
printString("A", () => {
printString("B", () => {
printString("C", () => {});
});
});
};
printAll();
// A B C
pending : 대기 (아무것도 안함)
fulfill : 이행 (연산이 성공적으로 완료)
reject: 거부 (연산 실패함)
예시 1.
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();
예시 2. 더 깔끔하게
function eatLunch() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("3.eatLunch");
}, 100);
});
}
function eatDinner() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("4.goToBed");
}, 100);
});
}
eatLunch()
.then((data) => {
console.log(data);
return eatDinner();
})
.then((data) => {
console.log(data);
return console.log("sleep");
});
예시 3. 커피 예시로 보는 비동기
// 시작 시간과 현재 시간 비교해 ms 범위 내에서 무한 로프 도는 blocking 함수
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(2000);
return coffee
}
let customers = [
{name: "joo" , request: "latte"}, {name: "jon", request: "espa"}];
customers.forEach(function(customer) {
let coffee = orderCoffeeSync(customer.request);
drink(customer.name, coffee);
});
//latte가 주문되었습니다
//joo는latte를 마십니다
//espa가 주문되었습니다
//jon는espa를 마십니다
참고 :
이벤트 루프 참고 영상 : 이해가 기가 막힌다.
https://www.youtube.com/watch?v=wcxWlyps4Vg&ab_channel=%EC%9A%B0%EC%95%84%ED%95%9CTech
참고 1 : https://velog.io/@cadenzah/What-is-a-Promise
참고 2 : https://joshua1988.github.io/web-development/javascript/promise-for-beginners/
코딩을 배우는 게 아니라 뭔가 컴퓨터 공학적인? 기계의 작동원리를 공부하는 기분. 좋다.
웹 프로그래밍 공부하면서 callback, promise를 여러 번 사용하고 공부했지만 명확한 이해는 부족했는데, 이번 기회에 확실하게 알 수 있었다.
js 엔진의 구조를 새로 배웠고, 브라우저의 구조와 작동 원리를 명확하게 배울 수 있었다.
과제 test 도중 에러를 발견했고, 구글링에도 안되는 걸 스스로 해결하고, 공유했다. 더 나은 솔루션도 제안 받았고, 적극성과 자신감, 소속감이 올라갔다.
페어는 뭐 이제 그냥 별 생각없이 들어가도 될 거 같다.
드디어 주말이다 이십
ㅍ