How to do several asynchronous I/O actions in Dart cleanly (Isolates)?
Asked Answered
I

1

8

In Dart, there is a concept of Isolates. I have an application (that I'm experimenting in Dart) that has lots of asynchronous IO where each call (they are database calls) are dependent on the previous one. So I have ended up in a nested callback hell.

I was wondering if Isolates could solve that nested callback soup, but it looks a bit verbose and I'm not sure if it fits it well.

There are also Generators proposed in the next ECMAScript Harmony which could solve these things, but how would you currently do lots of asynchronous IO in Dart in a clean way?

Indefatigable answered 7/2, 2012 at 21:34 Comment(0)
R
6

You can use Future's and Completers to chain work together. The following future returns the result of a 'ls' command from a process:

Future<String> fetch(String dir) { 
  final completer = new Completer(); 
  Process process = new Process.start('ls', [dir]);
  process.exitHandler = (int exitCode) {
    StringInputStream stringStream = new StringInputStream(process.stdout);
    stringStream.dataHandler = () {
      String content = stringStream.read();
      completer.complete(content);
      process.close();
    };
  };
  process.errorHandler = (var error) { 
    completer.completeException(error); 
    return true; 
  }; 
  return completer.future; 
}; 

which you can then chain together like this:

fetch('/').then((val) => fetch("/usr").then((val) => fetch("/tmp")));

Not the most pretty solution but this is what I get by with now.

Rhodic answered 7/2, 2012 at 23:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.