비동기 작업을 조금 더 편하게 처리 할 수 있는 객체
이전에는 비동기 작업을 처리 할 때에는 콜백 함수로 처리를 해야 했었는데요, 콜백 함수로 처리를 하게 된다면 비동기 작업이 많아질 경우 코드가 쉽게 난잡해지게 되었습니다.
한번 숫자 n 을 파라미터로 받아와서 다섯번에 걸쳐 1초마다 1씩 더해서 출력하는 작업을 setTimeout 으로 구현해보면
function increaseAndPrint(n, callback) {
setTimeout(() => {
const increased = n + 1;
console.log(increased);
if (callback) {
callback(increased);
}
}, 1000);
}
increaseAndPrint(0, n => {
increaseAndPrint(n, n => {
increaseAndPrint(n, n => {
increaseAndPrint(n, n => {
increaseAndPrint(n, n => {
console.log('끝!');
});
});
});
});
});
코드 읽기가 복잡하죠? 이런 식의 코드를 Callback Hell (콜백지옥) 입니다.
비동기적으로 처리해야 하는 일이 많아질수록, 코드의 깊이가 계속 깊어지는 현상이 있는데요, Promise 를 사용하면 이렇게 코드의 깊이가 깊어지는 현상을 방지 할 수 있습니다.
let fetched = fetch("https://jsonplaceholder.typicode.com/todos/1");
console.log(fetched)
// Promise{...}
fetch는 Promise 객체를 반환한다.
promise는 두 개의 메서드를 사용할 수 있는데 then과 catch이다. 둘 다 콜백 함수를 받는다.
fetch를 통해서 실행한 결과가 성공했을 때 then으로 전달된 콜백 함수가 호출된다.
그 콜백함수가 호출되면서 결과값이 있다면 첫 번째 파라미터로 받을 수 있다.
fetched.then((result)=>{});
fetch를 통해서 실행한 결과가 실패한다면 catch 안으로 전달된 콜백함수가 호출된다.
파라미터로 이유를 알려준다.
fetched.catch((reason)=>{});
그래서 데이터를 받아오는 공식처럼 사용되는 아래 코드를 보면
이전까지는 그냥 외우다시피 하면서 썼었는데 이번에 promise에 대해 공부하면서
이제 더 이해가 되는 것 같다
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json()) // response.json() => 아직 promise상태
.then((data) => console.log(data));
async는 function 앞에 위치하는데 async가 붙은 함수는 반드시 promise를 반환하고,
promise가 아닌 것은 프라미스로 감싸 반환한다.
const func02 = async function () {
// (1) 데이터 1 받아오기
const result1 = await fetch("http://~~~");
// (2) 데이터 2 받아오기
const result2 = await fetch("http://~~~", result1);
};
func02();
const func03 = async () => {
await fetch("http://~~~");
};
자바스크립트는 await 키워드를 만나면 프라미스가 처리될 때까지 기다린다.
Promise.then으로 프로미스를 벗겨서 promise 안의 값을 꺼내올 수 있다.
데이터를 받아오는 용도가 아니다.
const result1 = await fetch("https://jsonplaceholder.typicode.com/todos/1"); // 1
const result2 = await fetch(
"https://jsonplaceholder.typicode.com/todos/1",
result1
); // 2
const result3 = await fetch(
"https://jsonplaceholder.typicode.com/todos/1",
result2
); // 3
const result4 = await fetch(
"https://jsonplaceholder.typicode.com/todos/1",
result3
); // 4
if (result1.code === "성공") {
alert("성공입니다.");
} else {
alert("실패입니다.");
}