Home > Software design >  Getting Promise instead of actuall value in React
Getting Promise instead of actuall value in React

Time:10-08

Hi I'm using axios to call API, Now the problem is Whenever I call API it's returning promise with Array as a result instead of actual value.

Here is the code:

export const GetResults=async(arrays)=>{debugger

  let res=await  arrays?.map(async (i) => {
   
  const response= await callAPI(i);
   return  response
   
   })
   return res
}

import {GetResults} from'../../someFun'

  const callMe=async()=>{debugger
   const res=  await GetResults(["1","2","3")
   console.log( res)========/Promise
  }


const callAPI = (
  id?: string,
): Promise<void> => {
  const params = {
    id: id,
  };

  return api
    .get<>('api end point', { params })
    .then(({ data }) => data)
    .catch((err) => {
      return err;
    });
};

How to get actual return value instead of promise

CodePudding user response:

May be const res= await GetResults(["1","2","3"]).toPromise() will work.

CodePudding user response:

You can use Promise.all to return all the resolved promises:

async function callAPI(i) {
  return `API response: ${i}`;
}


async function getResults(arrays) {
  const apiCalls = arrays?.map(async (i) => callAPI(i));
  return Promise.all(apiCalls);
}

async function callMe() {
  const res = await getResults(["1", "2", "3"]);
  console.log(res);
}

callMe();

  • Related