skip to Main Content

Let’s say I have 4 API calls that might call more APIs. Then, I go into main() {} and I write

api1();
api2();
api3();

While the body of each is:

{
 await getData();
 getMoreData();
 getMoreData();
}

Note that I don’t have awaits in main and also in my function body.

My question is, will that mean that the first 3 functions will be executed at the same time and then when the others run, they will also be at the same time?

2

Answers


  1. Yes you can do so by the use of Future.wait and Future.any functions.

    Future.wait() completes when all the futures in the list complete successfully. If any future in the list fails with an error, the returned future will also fail with that error.

    Future.any() completes as soon as any of the futures in the list completes successfully. The returned future will complete with the value of the first future in the list that completes successfully.

    Here is a sample code that may work for you:

        Future<void> runAsyncFunctions() async {
        // Create a list of futures
        List<Future<void>> futures = [
        asyncFunction1(),
        asyncFunction2(),
        asyncFunction3(),
        ];
      
        // Wait for all the futures to complete
        await Future.wait(futures);
      
       // All the futures have completed at this point
       }
    
    Login or Signup to reply.
  2. My question is, will that mean that the first 3 functions will be executed at the same time and then when the others run, they will also be at the same time?

    It depends on exactly what you mean by "at the same time". When you do:

    void main() {
      api1();
      api2();
      api3();
    }
    

    and if api1, api2, and api3 are all asynchronous, then they will run concurrently. They might or might not run in parallel.

    Note that if api1, api2, and api3 each returns a Future, then none of those Futures are awaited and you will not be notified when any or all of them complete. If you want to be notified when all of them complete, then use Future.wait. If you don’t care and want to treat them as fire-and-forget operations, then Future.wait isn’t necessary.

    If you also want to silently swallow errors from api1, api2, and api3, then you should use the Future.ignore extension method:

    void main() {
      api1().ignore();
      api2().ignore();
      api3().ignore();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search