반응형
Promise
Promise
자바스크립트에서 제공하는 비동기를 간편하게 처리할 수 있는 Object로 콜백함수의 단점을 보완(fetch 함수는 Promise 객체를 리턴)
Promise 생성자를 보면 executor라는 콜백 함수를 전달하는데 이 콜백함수는 또 다른 두가지의 콜백함수(기능을 정상적으로 수행해서 마지막에 데이터를 전달하는 resolve, 기능에 문제가 생기면 호출하는 reject)를 받는다.
//promise를 만드는 순간 전달한 executor가 바로 실행(네트워크 통신을 작성한다면 바로 실행된다(원하지 않아도))
const promise = new Promise((resolve, reject) => {
console.log('promise');
});
const promise = new Promise((resolve, reject) => {
console.log('promise');
setTimeout(() => {
resolve('network ok'); // 기능을 잘 수행했다면
}, 2000);
});
then, catch, finally
promise 변수를 이용해서 수행이 잘 된다면 값을 받아와서 원하는 기능을 수행할 때 then, catch, finally를 쓴다
then - promise가 잘 수행이 되어서 최종적으로 resolve라는 콜백함수를 통해서 전달한 값이 value의 파라미터로 전달된다.
const promise = new Promise((resolve, reject) => {
console.log('promise');
setTimeout(() => {
resolve('network ok'); // 기능을 잘 수행했다면
}, 2000);
});
promise.then((value) => {
console.log(value);
});
reject 일 때
const promise = new Promise((resolve, reject) => {
console.log('promise');
setTimeout(() => {
reject(new Error('error'));
}, 2000);
});
promise
.then((value) => {
console.log(value);
}) // catch를 쓰지 않으면 에러가 발생함 Uncaught(in promise)
.catch((error) => {
// catch를 쓰면 new Error의 인자값을 error로 받는다
console.log(error); // error
});
finally - 성공이든 실패든 무조건 실행
const promise = new Promise((resolve, reject) => {
console.log('promise');
setTimeout(() => {
reject(new Error('error'));
}, 2000);
});
promise
.then((value) => {
console.log(value);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log('finally');
});
Promise chaining
then을 여러번 묶어서 다른 비동기처리를 할 수 있다. 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, rejct) => {
setTimeout(() => resolve(num * 4), 1000);
});
})
.then((num) => {
console.log(num); // 24
});
Promise chaining 에러 처리법
- resolve만 받을 때는 문제가 없다.
const getClothes = new Promise((resolve, reject) => {
setTimeout(() => resolve('1. 옷을 입다 '), 1000);
});
const openDoor = (cloth) =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${cloth} 2.문을 연다`), 1000);
});
const goOut = (door) =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${door} 3. 밖으로 나간다`), 1000);
});
getClothes
.then((cloth) => openDoor(cloth))
.then((door) => goOut(door))
.then((sentence) => console.log(sentence));
// 콜백함수를 받을 때 받아온 하나를 바로 호출하는 경우에는 아래 처럼 생략 가능
// getClothes
// .then(openDoor)
// .then(goOut)
// .then(console.log);
- reject를 받으면 에러가 발생한다.
에러를 핸들링 하는 코드가 없기 때문에 에러가 발생한다.
-> catch로 여러가지 경우를 만들면 다양한 상황을 해결할 수 있다.
const getClothes = new Promise((resolve, reject) => {
setTimeout(() => resolve('1. 옷을 입다 '), 1000);
});
const openDoor = (cloth) =>
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(`${cloth} 2.문을 연다`)), 1000);
});
const goOut = (door) =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${door} 3. 밖으로 나간다`), 1000);
});
getClothes
.then((cloth) => openDoor(cloth))
.catch(error=> '2. 창문을 연다')
.then((door) => goOut(door))
.then((sentence) => console.log(sentence))
.catch(console.log);
반응형
'자바스크립트' 카테고리의 다른 글
자바스크립트 동작 원리 (0) | 2022.04.20 |
---|---|
[자바스크립트] 옵셔널 체이닝 (0) | 2022.03.28 |
[자바스크립트] this (0) | 2021.12.14 |
[자바스크립트] 빌트인 객체 (0) | 2021.12.13 |
[자바스크립트] strict mode (0) | 2021.12.09 |