1

上面的问题是在 Dart Google+ 社区提出的,并没有给出明确的答案,所以我想我会在这里重复这个问题,因为,我真的很想知道。这是 Dart 社区的帖子:

https://plus.google.com/u/0/103493864228790779294/posts/U7VTyX5h7HR

那么,无论有无错误处理,正确的方法是什么?

4

2 回答 2

3

您链接到的问题是关于异步读取多个文件的内容,这是一个更难的问题。我认为弗洛里安的解决方案没有问题。简化它,这似乎成功地异步读取了一个文件:

import 'dart:async';
import 'dart:io';

void main() {
  new File('/home/darshan/so/asyncRead.dart')
    .readAsString()
    ..catchError((e) => print(e))
    .then(print);

  print("Reading asynchronously...");
}

这输出:

异步读取...
导入“飞镖:异步”;
导入“飞镖:io”;

无效的主要(){
  新文件('/home/darshan/so/asyncRead.dart')
    .readAsString()
    ..catchError((e) => print(e))
    .then(打印);

  print("异步读取...");
}

作为记录,这是 Florian Loitsch 对初始问题的(稍作修改)解决方案:

import 'dart:async';
import 'dart:io';

void main() {
  new Directory('/home/darshan/so/j')
    .list()
    .map((f) => f.readAsString()..catchError((e) => print(e)))
    .toList()
    .then(Future.wait)
    .then(print);

  print("Reading asynchronously...");
}
于 2013-04-16T08:02:25.283 回答
3

Florian 解决方案的一个缺点(或没有)是它并行读取所有文件,并且仅在读取所有内容后才处理内容。在某些情况下,您可能希望一个接一个地读取文件,并在读取下一个文件之前处理一个文件的内容。

为此,您必须将期货链接在一起,以便下一个 readAsString 仅在前一个完成后运行。

Future readFilesSequentially(Stream<File> files, doWork(String)) {
  return files.fold(
      new Future.immediate(null), 
      (chain, file) =>
        chain.then((_) => file.readAsString())
             .then((text) => doWork(text)));
}

对文本所做的工作甚至可以是异步的,并返回一个 Future。

如果流返回文件 A、B 和 C,然后完成,则程序将:

run readAsString on A
run doWork on the result
when doWork finishes (or the future it returns completes) run readAsString on B
run doWork on the result
when doWork finishes (or the future it returns completes) run readAsString on C
run doWork on the result
when doWork finishes, complete the future returned by processFilesSequentially.

我们需要使用折叠而不是监听,以便我们获得一个在流完成时完成的 Future,而不是让 onDone 处理程序运行。

于 2013-04-16T15:09:04.623 回答