Reputation: 3071
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
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
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
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:
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