Dart API Referencedart:coreFutures

Futures Class

Futures holds additional utility functions that operate on Futures (for example, waiting for a collection of Futures to complete).

Static Methods

Code Future<List> wait(List<Future> futures) #

Returns a future which will complete once all the futures in a list are complete. If any of the futures in the list completes with an exception, the resulting future also completes with an exception. (The value of the returned future will be a list of all the values that were produced.)

static Future<List> wait(List<Future> futures) {
  if (futures.isEmpty()) {
    return new Future<List>.immediate(const []);
  }

  Completer completer = new Completer<List>();
  Future<List> result = completer.future;
  int remaining = futures.length;
  List values = new List(futures.length);

  // As each future completes, put its value into the corresponding
  // position in the list of values.
  for (int i = 0; i < futures.length; i++) {
    // TODO(mattsh) - remove this after bug
    // http://code.google.com/p/dart/issues/detail?id=333 is fixed.
    int pos = i;
    Future future = futures[pos];
    future.then((Object value) {
      values[pos] = value;
      if (--remaining == 0 && !result.isComplete) {
        completer.complete(values);
      }
    });
    future.handleException((exception) {
      if (!result.isComplete) {
        completer.completeException(exception, future.stackTrace);
      }
      return true;
    });
  }
  return result;
}