Leksat
Leksat

Reputation: 3071

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

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.
}

Upvotes: 8

Views: 4983

Answers (3)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76183

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...
}

Upvotes: 7

Chris Buckett
Chris Buckett

Reputation: 14388

No.

The whole point of acync APIs that when the async operation finishes, your code receives the result as a callback.

Another way to write your code, if you're looking to reduce nesting, could be by passing in a function to the then()

void main() {
  Process.run('some_shell_command', []).then(doSomethingWithResult);  
}

void doSomethingWithResult(result) {
   print(result.stdout); // I have the output here...
}

Upvotes: 0

Justin Fagnani
Justin Fagnani

Reputation: 11171

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.

Upvotes: 2

Related Questions