在Dart中使用Futures的循环 [英] Using loops with Futures in Dart

查看:1106
本文介绍了在Dart中使用Futures的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以我有一个文件列表,我需要在列表的每个成员上运行一个函数。我基本上想这样做:

Okay, so I have a List of Files and I need to run a function on each member of the list. I essentially want to do something like this:

for(File file in files) {
    functionThatReturnsAFuture(file);
}

但是显然这不会工作,因为返回Future的函数的异步。

But obviously this won't work, since the function that returns a Future fires of asynchronously. Is my only option something like this?

List<File> files = new List<File>();
// Add files somewhere

Future processFile(int i) {
   return new Future.sync(() {
       //Do stuff to the file
       if(files.length>i+1) {
           return processFile(i+1);
       }
   });
}

processFile(0);

编辑:
我想更多的上下文很重要。最终目标是将多个文件合并成一个JSON对象以提交到服务器。 FileReader对象使用事件来执行读取,所以我使用一个Completer来创建一个提供了Future的包装函数。我可以让所有这些异步运行,然后触发一个事件,提交它,当他们都完成了,但是这是相当多的设置与一个for-each循环,使它所有的工作(如果存在,反正)。核心问题是需要在文件列表上运行一个Future-returning函数,然后执行一个依赖于所有已完成的操作。

I suppose more context is important. The end goal is to combine several files into a single JSON object for submitting to a server. The FileReader object uses events to perform a read, so I used a Completer to create a wrapper function that provides a Future. I could let all of these run asynchronously, and then fire off an event that submits it when they are all done, but that's comparatively a lot of setup vs. a for-each-loop that makes it all work (if one exists, anyway). The core issue is needing to run a Future-returning function on a List of files and then perform an action that depends on them all having completed.

推荐答案

当您需要等待多个期货完成,而您不关心订单时,您可以使用 Future.wait()

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

如果顺序很重要,您可以使用 Future.forEach(),等待每个Future在移动到下一个元素之前完成:

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

这篇关于在Dart中使用Futures的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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