Promise 코드는 다음과 같이 작성한다.
const pro = new Promise ((resolve, reject) => { //code [성공] [실패] });어떤 일이 완료된후 실행되는 함수를 콜백함수라고 한다.
new Promise 생성자가 반환하는 객체는state와 result를 객체로 갖는다
초기에 state는 pending(대기), result는 undefined 이다
성공 resolve(value) 하면 state는 fulfilled(이행됨), result는 value이다
반대로 실패 reject(error)면 state는 rejected(거부됨), result는 error이다
* 새로운 Promise가 만들어질때, executor가 자동적으로 실행된다.!! const promise = new Promise((resolve, reject) => { console.log('doing something...'); setTimeout(() => { //resolve('tom'); //reject(new Error('no network')); //then을 이용해서 성공적 케이스만 다뤄서 Uncaught (in promise) Error 발생 }, 2000); });
then : Promise가 정상적으로 수행이 되서 최종적으로 resolve라는 콜백함수를 통해 전달한 값이 value로 전달되어 들어온다.then은 값을 전달하기도 하고 또다른 Promise를 전달하기도 한다.catch : error를 처리하기 위해 사용finally : 성공 실패 상관없이 어떤 기능을 마지막으로 실행시킬때 사용한다.promise //then을 호출하면 다시 Promise가 리턴 된다 .then((value) => { console.log(value); }) //리턴된 Promise에 catch를 등록한다. .catch(error => { console.log(error); }) .finally(()=>{ console.log('finally') });
const fetchNumber = new Promise((resolve, reject) => { setTimeout(() => { resolve(1) }, 1000); }); // 1초 뒤에 1이 fetchNumber에 전달된다 fetchNumber .then(num => num*2) // num에 1이 전달되고 2가 된다 .then(num => num*3) // 2가 전달되고 6이 된다 .then(num => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(num -1) }, 1000); }); }) // num에 6이 전달되고 1초뒤에 5가 된다 .then(num => console.log(num)); => 총 2초 뒤에 5가 나타나게 된다
const f1 = function(callback){
setTimeout(() => {
console.log('1번 주문완료');
callback();
}, 1000);
};
const f2 = (callback) => {
setTimeout(() => {
console.log('2번 주문완료');
callback();
}, 3000);
};
const f3 = (callback) => {
setTimeout(() => {
console.log('3번 주문완료');
callback();
}, 2000);
};
console.log('start');
f1(function(){
f2(function(){
f3(function(){
console.log('END')
});
});
});
depth가 깊어지면서 계속 콜백을 호출하는 것을 콜백지옥라고 한다.
Promise를 사용해서 콜백지옥을 벗어나게 다시 작성하면....
const f1 =() => {
return new Promise((res, rej) =>{
setTimeout(() => {
res('1번 주문완료');
}, 1000);
});
};
const f2 = (message) => {
console.log(message);
return new Promise((res, rej) => {
setTimeout(() => {
res('2번 주문완료');
}, 3000);
});
};
const f3 = (message) => {
console.log(message);
return new Promise((res, rej) => {
setTimeout(() => {
res('3번 주문완료');
}, 2000);
});
};
console.log('start')
f1()
.then((resolve) => f2(resolve))
.then((resolve) => f3(resolve))
.then((resolve) =>console.log(resolve))
.catch(console.log)
.finally(() => {
console.log('end');
});
reject되면 에러가 발생한다 배열을 받는다.
Promise.all([f1(), f2(), f3()]).then((resolve) => { console.log(resolve); });
Promise.all과 동일한 방식으로 작성한다.Promise.race([f1(), f2(), f3()]).then((resolve) => { console.log(resolve); });