0

I'm calling 4 asynchronous network functions in parallel, but I need to wait on one specific function to finish in order to continue my code.

Currently, here's what I've implemented:

async function callAllFuncs () {
    // I need to call the important one as it might be delayed in the Network system if there are already too many requests pending.
    // So having the important one first will be better, and might return faster than if I call it at the end

    const importantPromise = fetch('/a') // No await here, as I don't want to block
    fetch('/b')
    fetch('/c')
    fetch('/d')

    return await importantPromise // Now we wait!
}

Is there a better way to do that ?

(Calling all four functions and returning as soon as the important one has finished, regardless of the three others).


Calling Promise.all or Promise.allSettled doesn't work here because it will wait for all functions to either finish or fail. I don't want to wait for the three others at all, I just want to return as soon as '/a' has finished, regardless of the three others.

halfer
  • 19,824
  • 17
  • 99
  • 186
Cyril N.
  • 38,875
  • 36
  • 142
  • 243
  • 1
    `Is there a better way to do that?` No. – Stephen Cleary Jul 08 '21 at 15:39
  • Is there a problem with the code? If this is working code that you want reviewed, then ask on [Code Review](https://codereview.stackexchange.com/) – trincot Jul 08 '21 at 15:40
  • @StephenCleary Ok, that's clear :D – Cyril N. Jul 08 '21 at 15:45
  • @trincot Makes sense! Thank you – Cyril N. Jul 08 '21 at 15:45
  • 2
    @trincot The question would be off-topic if posted on Code Review. Please take extra care when recommending Code Review in the future. – Peilonrayz Jul 08 '21 at 15:53
  • 1
    @Peilonrayz Could you elaborate why it would be off-topic? From my understanding, the idea is to review if the suggested code above is good or can be improved. Isn't it the aim of "Code Review"? – Cyril N. Jul 08 '21 at 16:01
  • @CyrilN. We can't comment on code where all context is stripped away. Please see our [relevant meta](https://codereview.meta.stackexchange.com/a/3652). – Peilonrayz Jul 08 '21 at 16:05
  • @Peilonrayz, when I suggest Code Review, I am not suggesting the Asker should not follow the guidelines over there. I will keep recommending Code Review for code review. – trincot Jul 08 '21 at 16:18
  • See [Can I fire and forget a promise in ES7?](https://stackoverflow.com/q/32384449/1048572) - you should definitely add some error handling to the promises you are not `await`ing. Also the order of the `fetch()` calls is hardly important if you don't `await` them, so I would not use an extra `const importantPromise` but just call `return fetch('/a');` last. – Bergi Jun 27 '23 at 23:31

0 Answers0