wait property

Future<Map<K, V>> get wait

Creates a Map<K, V> from a Map<K, Future<V>>.

Like FutureIterable<T>.wait but waits on Map values (in parallel if possible).

The returned Future will complete only after all Future values have completed. If any of those Futures fails, completes with a ParallelMapWaitError.

Implementation

Future<Map<K, V>> get wait async {
  // Copy the keys now in case this `Map` is mutated while waiting.
  var keysCopy = [...keys];
  try {
    var awaitedValues = await values.wait;
    assert(keysCopy.length == awaitedValues.length);
    return Map.fromIterables(keysCopy, awaitedValues);

    // ignore: avoid_catching_errors
  } on ParallelWaitError<List<V?>, List<AsyncError?>> catch (e) {
    assert(keysCopy.length == e.values.length);
    assert(keysCopy.length == e.errors.length);

    var values = <K, V>{};
    var errors = <K, AsyncError>{};

    for (var i = 0; i < keysCopy.length; i += 1) {
      var error = e.errors[i];
      if (error == null) {
        values[keysCopy[i]] = e.values[i] as V;
      } else {
        errors[keysCopy[i]] = error;
      }
    }

    throw ParallelMapWaitError(values, errors);
  }
}