데이터 싱크가 중요한 경우
유저에게 빠른 피드백이 필요한 경우는 데이터 요청을 해놓고 바로바로 화면을 갱신해주는 경우
const promise = new Promise((resolve, reject) => {
// resolve, reject의 이름은 정해져있지않다. 매개변수의 이름 우리가 정해줘도 된다. 보통은 (resolve, reject) 라고 쓴다.
/*
시간이 오래 걸리는 실행문 ... 5초
*/
resolve();
reject();
});
// resolve() > then() reject() > catch로 호출된다.
promise.then(() => {
console.log('1. promise() then() called'); // 호출을 먼저 했는데 결과가 마지막에 나왔다.
}).catch(() => {
console.log('2. promise() catch() called');
});
// 선언이 어디에 되있든 상관은 없고 언제 호출을 했느냐가 중요하다.
// 동기 처리
function testFun1() {
console.log('testFun1()');
let startTime = new Date().getTime(); // Date라는 객체를 써서 현재시간을 가져온것
while(new Date().getTime() - startTime < 5000); // while이 true때 반복이 되기 때문에 startTime < 1000으로 해야한다.
testFun2();
}
function testFun2() {
console.log('testFun2()');
}
testFun1();
// testfun1 testfun2 가 처리가 되고 promise가 처리가 된다. 컴파일과 런타임사이에 서순이 다르기 때문에 컴파일 단계에서 testfun1이 호출된다는 사실을 알고 있다.
// new 를 써서 메모리를 동적할당이 된다는 사실은 런타임중에 알게 되서 console.log promise() then() called가 늦게 찍힌다.
