오늘 드디어 심화 강의 주차가 끝이 났다..!
앞으로도 힘든일은 많겠지만 지금까지 중에선 가장 힘들었던 일주일이였다. 잘 알지도 못하는 상태에서 정말 많은 양의 지식을 머리에 넣으려니까 너무 힘들었는데, 너무 다행스럽게도 다른 분들의 코드를 볼 수 있는 기회가 많이 있었어서 그 지식들을 어느정도 소화시킨것 같기도 하다.
오늘은 이번주에 강의를 들으면서 정말 궁금했으나 깊게 찾아보지 못했던 키워드인
async-awite과 then의 차이를 정리 해보려고 한다.
async-awite는 Node.js의 또 다른 핵심요소인 제너레이터에서 파생된 형식이다.
console.log("1");
const promise = new Promise(function (resolv, reject) {
setTimeout(function () {
resolv("success");
}, 1000);
});
console.log("2");
promise.then(function (value) {
console.log(value);
});
console.log("3");
위 코드는 then을 사용한 예시이다.
해당 코드를 돌려보면 1 -> 2 -> 3 -> success의 순서로 콘솔이 찍힌다.
Promise 객체를 가지고 있는 promise라는 함수가 존재하고, 얘는 내부로직이 끝났을 때 resolve를 던진다. 예시의 내부로직은 setTimeout이기 때문에 1초가 지난 후에 resolve가 실행되는 것이다.
resolv가 던진 success라는 value는 resolv에 담겨있다.
promise가 끝나고 나서야 then이 실행되는데, promise가 성공적으로 실행된다는 전제하에 resolve에 있는value를 then으로 던진다.
value를 받은 then은 value를 사용하여 자신의 로직을 처리하게 된다.
import { async } from "@firebase/util";
console.log("1");
const promise = new Promise(function (resolv, reject) {
setTimeout(function () {
resolv("success");
}, 1000);
});
console.log("2");
async function thenFunction() {
console.log("thenFunction 함수 진입");
const result = await promise;
console.log(result);
}
console.log("3");
thenFunction();
console.log("4");
위 예시를 async-awite 구문을 이용하여 동일하게 처리 했다.
1 -> 2 -> 3-> thenFunction 함수 진입 -> 4 -> result 순서로 찍힌다.
3이 찍히는 시점 다음에 thenFunction을 콜하므로, thenFunction로직을 타지만 promise 함수는 비동기 처리가 되어 있어 완료할 때까지 멈춘다.
따라서 4가 먼저 찍히고 완료 후 success가 찍힌다.
차이점