Vlad Z.
Vlad Z.

Reputation: 3451

How to chain multiple futures in order

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.

Upvotes: 0

Views: 335

Answers (1)

Michael Horn
Michael Horn

Reputation: 4089

Because Dart begins running a Future's computation immediately upon the creation of that Future, the only practical way to do this is to create each Future immediately prior to awaiting their result, rather than mapping all the values to Futures up-front.

What that will look like is something like this:

void foo(List<int> uniqueIds) async {
  for (final uniqueId in uniqueIds) {
    await APIService.shared
        .networkingRequest(input: uniqueId)
        .then((value) => update())
        .onError((error, stackTrace) {
          handleError(error);
        });
  }
}

Upvotes: 1

Related Questions