1

I have a function getData() like this:

const getData = () => {
 const lsData = dummyJsonDataForTest;
 if (condition) {
  return lsData;
 }
 // call API here
 apiService
  .getData()
  .then((json) => {
    return json.data; 
  })
  .catch(() => {
    return null;
  })
 return null;
};

I want to return a response from the API call if the condition is false, but seems that the function getData() will return null before the API response.

Is there any way to make it wait for the response before the function return null?

Thank you in advance.

Tram Ngoc
  • 11
  • 1
  • You need to understand asynchronous javascript. I'd recommend looking here: https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call Whatever you fix in this function is most likely going to trickle down into the calling function. That is, if you await the promise here, this function will then become asynchronous, and you'll need to await the promise upstream. – Tom Apr 28 '22 at 18:02
  • I think is duplicated question you can find your answer https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Ayush Rana Sep 23 '22 at 04:28

0 Answers0