0

How to call async function from regular sync function?

getCategoryAll() doesn't work on page load as it works correctly when I type it into console. What I should change to make my function call giving an output that I expect?

async function getCategory(catId) {
    const response = await axios.get...
    // my code here
}

function getCategoryAll() {
   // my for loop logic here referring to getCategory(catId)
}

getCategoryAll()

Right now solution what I have is delaying execution of 2nd function which is obviously not the best solution

setTimeout(() => getCategoryAll(), 500);
Koke Abeke
  • 107
  • 7
  • 2
    A few things. Async always returns a promise: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#return_value so you should try to handle that in a different way. Second take a look at these links: https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState and this video to get more information and details: https://youtu.be/_iq1fPjeqMQ – Rodrigo Aug 19 '22 at 15:50
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function –  Aug 19 '22 at 16:07
  • What are you trying to do with the populated array? Whatever it is, you'll need to wait for the http request, there's no way to do it synchronously. – Bergi Aug 19 '22 at 23:05
  • Yes, getCategoryAll() should run after async getCategory() is completed. I tried to use setTimeout for getCategoryAll(), did not work. I tried to create async getCategoryAll() , also didn't help. I am new to JS, and Promises too confusing for me. – Koke Abeke Aug 19 '22 at 23:19
  • I want to have CATEGORIES_ARR filled on page load.. – Koke Abeke Aug 19 '22 at 23:21
  • Does this answer your question? [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – evolutionxbox Aug 22 '22 at 08:28

0 Answers0