Promise도 배열에 담을 수 있다.

Hunter Joe·6일 전
0
  async collectForexRate() {
    try {
      const exchangeRates = await Promise.allSettled([
        this.forexClient.fetchUsdKrwRate(),
        this.forexClient.fetchUsdJpyRate(),
        this.forexClient.fetchUsdEurRate(),
        this.forexClient.fetchUsdGbpRate(),
        this.forexClient.fetchUsdCnyRate(),
      ]);

      const redisPromises: Promise<void>[] = [];
      const currencies = ['krw', 'jpy', 'eur', 'gbp', 'cny'];

      exchangeRates.forEach((result, index) => {
        if (result.status === 'fulfilled') {
          const rate = result.value.toString();
          redisPromises.push(
            this.redisService.set(`usd-${currencies[index]}-rate`, rate, 300),
          );
        } else {
          this.logger.warn(
            `Failed to fetch ${currencies[index]} rate: ${result.reason}`,
          );
        }
      });

      await Promise.all(redisPromises);

      this.logger.log('Successfully collected and cached exchange rates');
    } catch (error) {
      this.logger.error(
        'Unexpected error occurred while collecting exchange rate',
        error.stack || error,
      );
    }
  }

이 코드의 목적:
모든 Redis 저장 작업을 동시에 실행 (병렬 처리)
각 작업이 순차적으로 실행되는 것보다 더 빠름
모든 작업이 완료될 때까지 기다림
하나라도 실패하면 에러를 throw
만약 이 코드가 없다면:
각 Redis 저장 작업이 순차적으로 실행됨
전체 실행 시간이 더 길어짐
실패한 작업을 확인하기 어려움

const redisPromises = [
  this.redisService.set('usd-krw-rate', '1300', 300),
  this.redisService.set('usd-jpy-rate', '150', 300),
  this.redisService.set('usd-eur-rate', '0.92', 300),
  this.redisService.set('usd-gbp-rate', '0.79', 300),
  this.redisService.set('usd-cny-rate', '7.2', 300)
];

await Promise.all(redisPromises);

forEach에서 this.redisService.set()을 호출할 때는 Promise를 배열에 추가만 하고 실제로 실행은 하지 않습니다.

profile
Async FE 취업 준비중.. Await .. (취업완료 대기중) ..

0개의 댓글

관련 채용 정보