Home > Software engineering >  Dynamically resolve Promise.all responses for each API call and store data
Dynamically resolve Promise.all responses for each API call and store data

Time:04-01

I'm passing right now 3 API calls to Promise.all. For now for each API call i need to create separate Error handler and if data is being return store to it's own object (corresponding to same API object name).

If i pass test4 to Promise.all how can i make it generate it's own error and storing data to state object, instead of my manually adding those values?

I have tried loop the response but getting Object { test3: Promise { "fulfilled" } } and no data.

Code:

import { useCallback, useEffect } from 'react'

const getTest1 = Promise.resolve({ isData: true, isError: false })
const getTest2 = Promise.resolve({ isData: false, isError: true })
const getTest3 = Promise.resolve({ isData: true, isError: false })

export const PromiseAll = () => {
  const getInitialData = useCallback(async () => {
    try {
      const res = await Promise.all([{ test1: getTest1 }, { test2: getTest2 }, { test3: getTest3 }])

      for (let i = 0; i < res.length; i  ) {
        const el = res[i]
        console.log('           
  • Related