Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to run Dart's Future synchronously?

Tags:

dart

How can I get Future's result immediately? For example:

void main() {
  Process.run('some_shell_command', []).then((ProcessResult result) {
    print(result.stdout); // I have the output here...
  });
  // ... but want it here.
}
like image 353
Leksat Avatar asked Feb 11 '13 20:02

Leksat


2 Answers

the support of await is in experimental state and can be used like:

void main() async {
  ProcessResult result = await Process.run('some_shell_command', []);
  print(result.stdout); // I have the output here...
}
like image 110
Alexandre Ardhuin Avatar answered Nov 11 '22 00:11

Alexandre Ardhuin


Sorry, it's simply not possible.

There are some cases where a function returns new Future.immediate(value) and conceivably you could get the value, but:

  1. This isn't one of those cases. Processes are run completely asynchronously by the VM.
  2. The ability to access a Future's value directly has been removed in the libv2 update.

The way to handle this is to have the function containing Process.run() return a Future, and do all your logic in the callback, which you seem to know, so I'm assuming that your code here is just an example and you're not really doing this in main(). In that case, unfortunately, you're basically out of luck - you have to make make your function async if you depend on knowing the future value or that the operation has completed.

Async in a single-threaded environment, like Dart and Javascript, is viral and always propagates up your call stack. Every function that calls this function, and every function that calls them, etc., must be async.

like image 37
Justin Fagnani Avatar answered Nov 10 '22 23:11

Justin Fagnani