728x90
반응형

프로미스(Promise)

결괏값을 갖고 있는 나중에 까볼 수 있는 상자 -> 코드의 순서를 실행 순서와 맞출 수 있음

setTimeout을 프로미스로 만들어쓰기

setTimeoutPromise로 만들어야 함 → async/await + setTimeout


      
const delay = (ms) =>
new Promise((resolve, reject) => {
setTimeout(resolve,ms);
});
await delay(3000);
console.log('3초 뒤');

async/await vs Promise.all

  • async/await: 순차적
  • Promise.all: 동시

Promise.all 말고 Promise.allSettled


      
const a = Promise.resolve('a')
const b = Promise.reject('b')
const c = Promise.resolve('c')
await Promise.all([a, b, c])

⇒ 하나라도 실패하면 나머지 두 개의 결과 알 수 없음

But, Promise.allSettled 보다 빠름


      
await Promise.allSetteld([a, b, c])

⇒ 배열에 세 개의 결과가 각각 담겨 있음

  • { status: ‘fulfilled’, reason: 성공 데이터 }
  • { status: ‘rejected’, reason: 에러 내용 }

await 과 then을 같이 쓰면 어떻게 될까

  • Promise 아니면 그 값 리턴
  • Promise라면 resolve하고 반환

awaitthen까지 전부 기다린 후에 awaitPromise 체인이 전부 resolve 된 다음에 값을 반환


      
try {
await Promise.reject('error happend')
} catch (err) {
console.log(err);
}

      
await Promise.reject('error happend')
.catch(console.log);

Promise.race 로 타임아웃 만들기

: 배열 안에 든 Promise 중에 가장 먼저 끝나는 애를 리턴하는 메서드

실행은 되지만, 결과가 나타나진 않음


      
Promise.race(
[Promise.reject('a)', Promise.resolve('b')]
);

Promise에 타임아웃을 거는 용도


      
Promise.race([
fetch('/api/users/123'),
new Promise((resolve, reject) => {
setTimeout(() =>
reject(new Error("시간 초과")),
5000);
}),
]);

Promise.race vs Promise.any

: resolve 된 애 중에 빠른 것을 리턴


      
Promise.any(
[Promise.resolve('a'), Promsie.resolve('b')]
);

⇒ a 리턴


      
Promise.any(
[Promise.reject('a'), Promsie.resolve('b')]
);

⇒ b 리턴


      
Promise.any(
[Promise.reject('a'), Promsie.rejcet('b')]
);

⇒ 모두 다 실패 → AggregateError 발생

 

두 api 간 먼저 성공한 것을 리턴


      
Promise.any(
[
fetch('/api/users/me'),
fetch('/api/users/you'),
]
).then(console.log);

⇒ 둘 중 하나라도 성공할 때까지 기다림 → 무조건 성공하는 결과


Promise.withResolvers


      
const delay = (ms) =>
new Promise((resolve, reject) => {
setTimeout(resolve,ms);
});
// 개선 문법
const delay = (ms) => {
const { promise, reject, resolve } = Promise.withResolvers();
setTimeout(resolve, ms);
return promise;
})

async 함수 return에 await이 필요한 경우

try, catch 안에서 에러를 잡고 싶은 경우


      
async function main() {
try {
return await Promise.reject('에러');
} catch (err) {
console.log('에러')
console.error(err);
}
}
await main();

await에 들어갈 수 있는 thenable

Promiseresolve 해주는 것이 아니라 thenablethen을 호출 ⇒ Promisethenable

(thenablePromise X)


      
await {
then(fulfilled) { fulfilled(123) }
}
// 123

객체가 Promsie인지 확인하는 법


      
const obj = Promsie.resolve('ok')
obj instanceof Promise;

thenable인지 같이 확인할 수 있는 방법


      
const thenable = {
then(fulfilled, rejected) {
fulfilled(123);
}
}
thenable instanceof Object
&& 'then' in thenable
&& typeof thenable.then === 'function'

출처

 

 

 

728x90
반응형
김앩옹