'How to make a function asynchronous?
Why doesn't the execution of f in the following code happen asynchronously after the main function. I expect it to be scheduled for execution from the event loop. Returning some Future doesn't help either.
void f() async {
print('f');
}
void main() {
print('main start');
f();
print('main end');
}
Output:
main start
f
main end
Solution 1:[1]
Marking a function async doesn't make what's going on inside the function async or change how the caller handles it. Any synchronous code inside a function marked async will still be run synchronously until the first async function call is hit.
To call print('f') asynchronously, construct a new Future.
void f() {
Future(()=>print('f'));
}
void main() {
print('main start');
f();
print('main end');
}
Or you could construct the future in main if you'd like:
void f() {
print('f');
}
void main() {
print('main start');
Future(f);
print('main end');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christopher Moore |
