동기 : 코드가 순차적으로 실행되는 것
비동기 : 특정 코드의 연산이 끝날 때까지 코드의 실행을 멈추지 않고 다음 코드를 먼저 실행하는 것
console.log("1");
setTimeout(() => console.log("2"), 2000);
console.log("3");
// Synchronous callback
function printImmediately(print) {
print();
}
printImmediately(() => console.log("hello"));
// Asynchronous callback
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(() => console.log("async"), 2000);
// 1
// 3
// hello
// 2
// async
1) pending : 초기상태
2) fulfilled : 작업이 성공적으로 완료됨
3) rejected : 작업이 실패함
parameter로 'executor'라고 불리는 함수를 받고, 이 함수는 resolve
와 reject
함수를 받는다.
응답이 성공적으로 완료되면, resolve
함수를 호출하고
오류가 발생하면, reject
함수를 호출한다.
새로운 promise 함수가 만들어지면, 자동적으로 executor가 실행된다.
(불필요한 네트워크 통신을 하게 될 수도 있다.)
executor 함수의 연산 이후 resolve 함수로 넘겨주는 함수를 .then
으로 받을 수 있고,
실패 및 오류 발생시 .catch
를 통해 받을 수 있다.
.finally
는 결과와 관계없이 모두 받을 수 있다.
const promise = new Promise((resolve, reject) => {
console.log("doing something...");
setTimeout(() => {
// resolve("ellie");
reject(new Error("no network"));
}, 2000);
});
promise
.then((value) => {
console.log(value);
})
.catch((error) => {
console.log(error);
})
.finally(() => console.log("finally"));
.then 안에서는 값을 전달할 수도 있고, promise를 전달할 수도 있다.
const fetchNumber = new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000);
});
fetchNumber
.then((num) => num * 2)
.then((num) => num * 3)
.then((num) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num - 1), 1000);
});
})
.then((num) => console.log(num));
// 3초 후에 5가 출력됨
promise 를 사용하지 않고 (then, catch로 줄줄이 잇지 않아도) 간편하게 비동기 함수를 작성하는 방법
function 앞에 async
를 추가해주면 promise 기능을 하게 된다.
async 함수 안에서만 사용 가능하다. 해당 promise가 종료될 때까지 실행을 멈추고 기다린다.
let myFirstPromise = new Promise((resolve, reject) => {
setTimeout(function(){
const num = Math.floor((Math.random() * 10) + 1);
console.log(“number is “ + num);
resolve(num);
}, 250);
});
async function foo () {
const num = await myFirstPromise;
if(num % 2 === 0) {
console.log(“Even!”);
} else {
console.log(“Odd…”);
}
}
foo();
async 함수인 foo()
는 myFirstPromise를 await 시킴.
myFirstPromise 의 executor 함수가 실행되어 resolve 될때까지 기다림.
250ms 후에 resolve로 num 값을 던져주면,
그 이후에 if문이 실행된다.