Return a Promise when calling a function in the table: Try and return a Promise function call
P粉340264283
P粉340264283 2023-09-05 14:36:01
0
2
534
<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粉340264283
P粉340264283

reply all(2)
P粉970736384

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>
)
P粉832212776

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>
 )
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template