How to read files asynchronously in Dart?

dart

Solution

The question you linked to was about asynchronously reading the contents of multiple files, which is a harder problem. I think Florian's solution has no issues. Simplifying it, this seems to successfully read a file asynchronously:

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...");
}

This outputs:

Reading asynchronously...
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...");
}

For the record, here's Florian Loitsch's (slightly modified) solution to the initial problem:

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...");
}

Problem

The above question was raised at the Dart Google+ community, and no clear answer was given, so I thought I'd repeat the question here because, well, I'd really like to know. Here's the post from the Dart community: https://plus.google.com/u/0/103493864228790779294/posts/U7VTyX5h7HR So what is the proper methods to do this, with and without error handling?

Original source