skip to Main Content
let data = [223, 34, 456, 56, 67];

function getDataFromApi(paramfromTableCell){
let postData = {data : paramfromTableCell}
   let result = apiResponse(url, 'post', postData).catch((err => console.log(err)))
   return result;
}

data.map((value)=>{
 return(
       <th>{getDataFromApi(value)}</th>
 )
})

Calling a function inside table cell but it’s returning a promise. On calling a function it takes a parameter and return the name as per number but it returning promise. Is there a way to resolve it?

2

Answers


  1. You have to await the promise to get the result. Otherwise you will just get the promise. So add async to your map function and then use await:

    data.map(async (value)=>{
      return(<th>{await getDataFromApi(value)}</th>
    )
    
    Login or Signup to reply.
  2. It looks like you using react. You need to save your responses into a react state for that.

    Here is a example code how it should look like (not tested):

    let data = [223, 34, 456, 56, 67];
    const [responses, setResponses]  = useState([]);
    
    useEffect(() => {
       const getAllResponses = () => Promise.all(
           data.map(val =>  getDataFromApi(val))
       );
    
       getAllResponses().then(responses => setResponses(responses));
    }, [data])
    
    function getDataFromApi(paramfromTableCell){
        let postData = {data : paramfromTableCell}
        return apiResponse(url, 'post', postData).catch((err => console.log(err)))
    }
    
    responses.map((value)=>{
     return(
           <th>{value}</th>
     )
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search