0

right now I have a recursive async function without awaits when it calls itself with Javascript, and it is using API calls, so it take some time to finish running.

This would be an example of that function:

var myFunction = async function(node){
    // takes some time with the API call and we wait
    var info = await getInfoFromAPI(node.uniqueId);

    // includes part of the info in a global tree variable

    // Will stop when there are no more nodes to process
    for(let i = 0; i < info.arrayOfNewNodes; i++){
        
        // All this calls would be without the await, to avoid processing time
        myFunction(info.arrayOfNewNodes[i]);
    }
}

The idea is that the user can fill stuff in forms while this loads, because it normally takes 2 minutes or something like this. Adding an await to the recursive call will increase the time to 15 minutes.

I need to check when there are no instances of that function to proceed with other logic, or in other words, I need to know when the functions finished their work.

Is there a way to check if there are instances of the function still running?

  • 1
    See the answers to the linked question for details, but basically instead of your `for` loop, do `await Promise.all(info.arrayOfNewNodes.map(myFunction));` That will make the recursive calls all at once, and then wait for them all to complete. Anything after that in the function won't be run until all of those promises are fulfilled. (If any of them is rejected, your function's promise will be rejected.) More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – T.J. Crowder Feb 02 '23 at 17:02
  • 1
    I hate to disagree with @T.J.Crowder who has a million reputation, but I think you don't want Promise.all(). I think you want Promise.allSettled(). I would set a flag `let isDone = false` and use `Promise.allSettled(promisesArray).then(() => isDone = true)`. You then don't have to worry if any of the promises throws an error. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled – jme11 Feb 02 '23 at 17:41
  • @jme11 - It depends on how the OP wants to handle errors. Definitely good to point to `allSettled` as a possible alternative, in case they want to handle errors individually with inline logic rather than having the whole thing fail in response to one failure. Having the whole process fail is *usually* what you want, but absolutely not always. Both have use cases. :-) – T.J. Crowder Feb 02 '23 at 18:17

0 Answers0