function runInDelay(seconds) {
return new Promise((resolve, reject) => {
if (!seconds || seconds < 0) {
reject(new Error('seconds가 0보다 작음'));
}
setTimeout(resolve, seconds * 1000);
});
}
runInDelay(2)
.then(() => console.log('타이머 완료!'))
.catch(console.error)
.finally(() => console.log('끝났다!'));
----------------------------------------------------------------------
function fetchEgg(chicken) {
return Promise.resolve(`${chicken} => 🥚`);
}
function fryEgg(egg) {
return Promise.resolve(`${egg} => 🍳`);
}
function getChicken() {
return Promise.reject(new Error('치킨을 가지고 올 수 없음!'));
}
getChicken()
.catch(() => '🐔')
.then(fetchEgg)
.then(fryEgg)
.then(console.log);
----------------------------------------------------------------------
function getBanana() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('🍌');
}, 1000);
});
}
function getApple() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('🍎');
}, 3000);
});
}
function getOrange() {
return Promise.reject(new Error('no orange'));
}
getBanana()
.then((banana) =>
getApple()
.then((apple) => [banana, apple])
)
.then(console.log);
Promise.all([getBanana(), getApple()])
.then((fruits) => console.log('all', fruits));
Promise.race([getBanana(), getApple()])
.then((fruit) => console.log('race', fruit));
Promise.all([getBanana(), getApple(), getOrange()])
.then((fruits) => console.log('all-error', fruits))
.catch(console.log);
Promise.allSettled([getBanana(), getApple(), getOrange()])
.then((fruits) => console.log('all-settle', fruits))
.catch(console.log);
- Promise(약속)
비동기적으로 수행하는 그리고 수행한 결과값을 끝났다고 알려주는 object이다.
프로미스 함수들
프로미스 병렬처리