Using loops with Futures in Dart

喜欢而已 提交于 2019-12-01 05:44:28

Dart supports async/await since quite some time which allows it to write as

someFunc() async {
  for(File file in files) {
    await functionThatReturnsAFuture(file);
  }
}
Pixel Elephant

When you need to wait for multiple Futures to complete and you don't care about the order, you can use Future.wait():

Future.wait(files.map(functionThatReturnsAFuture))
  .then((List response) => print('All files processed'));

If order is important you can use Future.forEach() instead which waits for each Future to be completed before moving to the next element:

Future.forEach(files, functionThatReturnsAFuture)
  .then((response) => print('All files processed'));

This library can help https://pub.dartlang.org/packages/heavylist

HeavyList<File> abc = new HeavyList<File>([new File(), new File(), ]);
abc.loop(new Duration(seconds: 1), (List<File> origin) {
print(origin);
}, (File item, Function resume) {
  //simulating an asynchronous call
  print(item);
  //move to next item
  resume();
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!