Home > Mobile >  How to chain multiple futures in order
How to chain multiple futures in order

Time:11-08

Given that I have the following data:

var uniqueIds = [1, 2, 3, 4];

I want to perform async requests in order based on the input above:

List<Future<void>> futures = uniqueIds.map((e) {
  return APIService.shared
      .networkingRequest(input: e)
      .then((value) => update())
      .onError((error, stackTrace) => {
          handleError(error)});
}).toList();

Where I want to trigger something like futures.waitInOrder(...) with whenComplete handler.

CodePudding user response:

The easiest way is to use await in a for-loop within an async method. This will wait for each future to complete before going on to the next:

Future<void> foo(List<int> uniqueIds) async {
  List<Future<void>> futures = uniqueIds.map((e) {
    return APIService.shared
        .networkingRequest(input: e)
        .then((value) => update())
        .onError((error, stackTrace) => {
            handleError(error)});
  }).toList();

  for (final future in futures) {
    final result = await future;
  }

  // Do something after all futures have completed.
}

The other alternative is to use Future.forEach - This function maps an Iterable to an output type, and if the output type is a Future, the futures are run one after the other, and the results of the computations are discarded:

Future.forEach(
  uniqueIds,
  (e) {
    return APIService.shared
      .networkingRequest(input: e)
      .then((value) => update())
      .onError((error, stackTrace) => {
          handleError(error)});
  }
).whenComplete((nullValue) {
  // Do something after all futures have completed.
});
  • Related