Script
async & await 본문
async & await
promise를 clear하게 사용하는 방법
경우에 따라 async & await을 사용해야할 떄와 promise를 사용해야 할때가 나뉜다
1.async
기존의 일반적인 Promise 문법
function fetchUser(){
return new Promise((resolve,reject)=>{
//do network request in 10 secs....
resolve('ellie');
});
}
const user=fetchUser();
user.then(console.log);
console.log(user);//Promise {<fulfilled>: 'ellie'}
//ellie
async를 사용시
async function fetchUser(){
//do network request in 10 secs....
return 'ellie';
}
const user=fetchUser();
user.then(console.log);
console.log(user);//Promise {<fulfilled>: 'ellie'}
//ellie
2.await
await은 async 내부에서만 사용 가능하고,
promise 함수가 fulfilled 혹은 rejected 될때까지 async 함수의 실행을 일시정지시킨다.
promise가 fulfilled되면 일시정지 시켰던 async 함수를 재실행시키고,
promise가 rejected되면 해당 함수를 throw시킨다.
function delay(ms){
return new Promise(resolve=>setTimeout(resolve,ms));
}
async function getApple() {
await delay(3000);
return '🍎';
}
async function getBanana() {
await delay(3000);
return '🍌'
}
async function pickFruits(){
const applePromise = getApple();
const bananaPromise = getBanana();
const apple = await applePromise;
const banana = await bananaPromise;
return `${apple}+${banana}`;
}
pickFruits().then(console.log);//🍎+🍌
3.유용한 Promis APIs
all- Promise 배열을 전달하게 되면 모든 Promise가 이행될때까지 기다렸다가
이행되고 나면, 그것들을 모두 담은 배열을 반환한다.
function pickALlFruits() {
return Promise.all([getApple(),getBanana()]).then(fruits=>
fruits.join('+')
);
}
pickALlFruits().then(console.log);//🍎+🍌
race- Promise 배열을 전달하게 되면 그중 가장 빨리 전달되는 것만을 반환한다.
function pickOnlyOne(){
return Promise.race([getApple(),getBanana()]);
}
pickOnlyOne().then(console.log);//🍎(사과의 delay가 1000,바나나의 delay가 2000이라고 가정시)'Javascript' 카테고리의 다른 글
| Closure (0) | 2022.12.07 |
|---|---|
| 호이스팅과 스코프, TDZ (0) | 2022.07.18 |
| Promise (0) | 2022.06.18 |
| Callback (0) | 2022.06.17 |
| JSON (0) | 2022.06.17 |
Comments