Async/Await feature in Dart 1.8

Update 2

The most recent nightly build also supports async*

void main() {
  generate().listen((i) => print(i));
}

Stream<int> generate () async* {
  int i = 0;

  for(int i = 0; i < 100; i++) {
    yield ++i;
  }
}

Update

yield and yield* in a method marked sync* (returning an Iterable) are already supported in 1.9.0-edge.43534

void main() {
  var x = concat([0, 1, 2, 3, 4], [5, 6, 7, 8, 9]);
  // x is an Iterable which iterates over the values 1 to 9
  print(x);
}

// A method marked `sync*` returns an `Iterable`
concat(Iterable left, Iterable right) sync* {
  yield* left;
  yield* right;
}
void main() {
  print(filter([0, 1, 2, 3, 4, 5], (x) => x.isEven));
}

filter(ss, p) sync* {
  for (var s in ss) {
    if (p(s)) yield s;
  }
}

async* generator functions (returning a Stream) are not yet supported.

Original

Basic support is already available.
See https://www.dartlang.org/articles/await-async/ for more details.

main() async {

  // await
  print(await foo());
  try {
    print(await fooThrows());
  } catch(e) {
    print(e);
  }

  // await for
  var stream = new Stream.fromIterable([1,2,3,4,5]); 
  await for (var e in stream) { 
    print(e); 
  }
}

foo() async => 42;

fooThrows() async => throw 'Anything';

Leave a Comment