Language/javascript

[JS] Promise.all()

khakhalog 2023. 10. 31. 09:46

순회 가능한 객체에 주어진 여러 개의 비동기 요청을 병렬적으로 실행시키고, 모든 요청이 처리되면 Promise 결과 값을 반환하는 메서드.

 

주어진 프로미스 중 하나가 거부하는 경우, 첫 번째로 거절한 프로미스의 이유를 사용해 본인도 바로 거부된다.

주의할 점은 실행 순서가 보장되지 않기 때문에 태스크의 순서가 보장될 필요가 없는 작업일 때 사용해야한다.

export async function fetchCardData() {
  try {
    const invoiceCountPromise = sql`SELECT COUNT(*) FROM invoices`;
    const customerCountPromise = sql`SELECT COUNT(*) FROM customers`;
    const invoiceStatusPromise = sql`SELECT
         SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS "paid",
         SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) AS "pending"
         FROM invoices`;
 
    const data = await Promise.all([
      invoiceCountPromise,
      customerCountPromise,
      invoiceStatusPromise,
    ]);
 
    const numberOfInvoices = Number(data[0].rows[0].count ?? '0');
    const numberOfCustomers = Number(data[1].rows[0].count ?? '0');
    const totalPaidInvoices = formatCurrency(data[2].rows[0].paid ?? '0');
    const totalPendingInvoices = formatCurrency(data[2].rows[0].pending ?? '0');
 
    return {
      numberOfCustomers,
      numberOfInvoices,
      totalPaidInvoices,
      totalPendingInvoices,
    };
  } catch (error) {
    console.error('Database Error:', error);
    throw new Error('Failed to card data.');
  }
}
 

'Language > javascript' 카테고리의 다른 글

[JS] 모듈(Module)  (1) 2023.12.12