Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 666
Tower Avatar asked Feb 07 '12 21:02

Tower


1 Answers

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.

like image 91
Lars Tackmann Avatar answered Sep 29 '22 05:09

Lars Tackmann