Dart中的异步可迭代映射 [英] Asynchronous iterable mapping in Dart

查看:65
本文介绍了Dart中的异步可迭代映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用异步映射功能映射一些Iterable吗?

Can I map some Iterable using async mapping function? Maybe it is a bug, that this code prints list of _Future imidiately, not ints after 1 or 5 seconds?

import 'dart:async';

Future<int> foo(int i) {
  var c = new Completer();
  new Timer(new Duration(seconds: 1), () => c.complete(i));
  return c.future;
}

main() {
  var list = [1,2,3,4,5];
  var mappedList = list.map((i) async => await foo(i));
  print(mappedList);
}


推荐答案

表达式(i)异步=> await foo(i)仍然返回一个将来。您可以使用 Future.wait(mappedList)等到所有创建的期货完成。

The expression (i) async => await foo(i) still returns a future. You can use Future.wait(mappedList) to wait till all created futures are completed.

这篇关于Dart中的异步可迭代映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆