问题 Dart 1.8中的异步/等待功能


它是1.8版本中的实验性功能,如枚举还是不是?我如何在Dart编辑器中使用它?是否有一篇很好的文章或示例应用程序可以让我开始这个?

当它仍然是一个实验性功能,推荐用于酒吧套餐?是否可以在pub包中使用该功能?


3302
2017-11-30 10:24


起源

看到 stackoverflow.com/a/27195775/217408 - Günter Zöchbauer


答案:


更新2

最近的每晚构建也支持 async* 

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

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

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

更新

yield 和 yield* 在标记的方法中 sync* 已经支持(返回Iterable) 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* 尚不支持生成器函数(返回Stream)。

原版的

基本支持已经可用。
看到 https://www.dartlang.org/articles/await-async/ 更多细节。

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';

11
2017-11-30 11:37