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
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:
It depends on exactly what you mean by "at the same time". When you do:
and if
api1
,api2
, andapi3
are all asynchronous, then they will run concurrently. They might or might not run in parallel.Note that if
api1
,api2
, andapi3
each returns aFuture
, then none of thoseFuture
s areawait
ed 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 useFuture.wait
. If you don’t care and want to treat them as fire-and-forget operations, thenFuture.wait
isn’t necessary.If you also want to silently swallow errors from
api1
,api2
, andapi3
, then you should use theFuture.ignore
extension method: