search

Home  >  Q&A  >  body text

Return a Promise when calling a function in the table: Try and return a Promise function call

<p><pre class="brush:php;toolbar:false;">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> ) })</pre> <p>Calling a function in a table cell, but it returns a Promise. When calling the function, it takes one parameter and returns the name based on the number, but it returns a Promise. Is there any way to solve this problem? </p>
P粉340264283P粉340264283520 days ago568

reply all(2)I'll reply

  • P粉970736384

    P粉9707363842023-09-06 12:12:35

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

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

    reply
    0
  • P粉832212776

    P粉8322127762023-09-06 00:30:22

    Looks like you are using React. You need to save your response into React's state.

    Here is a sample code, it should look like this (untested):

    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>
     )
    })

    reply
    0
  • Cancelreply