Dartlang wait more than one future

雨燕双飞 提交于 2019-11-27 02:35:21

问题


I want to do something after a lot of future function done,bu I do not know how to write the code in dart? the code like this:

for (var d in data) {
  d.loadData().then()
}
// when all loaded
// do something here

but I don't want to wait them one by one:

for (var d in data) {
  await d.loadData(); // NOT NEED THIS
}

how to write those code in dart?


回答1:


You can use Future.wait to wait for a list of futures:

import 'dart:async';

Future main() async {
  var data = [];
  var futures = <Future>[];
  for (var d in data) {
    futures.add(d.loadData());
  }
  await Future.wait(futures);
}

DartPad example



来源:https://stackoverflow.com/questions/42176092/dartlang-wait-more-than-one-future

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!