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

查看:39
本文介绍了在 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-loop 让它全部工作(如果存在,无论如何)).核心问题是需要对文件列表运行返回未来的函数,然后执行依赖于它们都已完成的操作.

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.

推荐答案

Dart 支持 async/await 因为很长一段时间允许它写为

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

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

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

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