Reputation: 121
import 'dart:async';
void main() async {
Future.microtask(() => print(1));
Future.value(2).then(print);
Future.sync(() => print(3));
Future.sync(() => 4).then(print);
}
Output I observe in dartpad:
3
1
2
4
Why didn't microtask get executed first?And what is different in the two Future.sync functions that printed them in different orders.
Upvotes: 2
Views: 85
Reputation: 31239
An important aspect with the .then()
method, is the following you can find in the documentation:
When this future completes with a
value
, the onValue callback will be called with that value. If this future is already completed, the callback will not be called immediately, but will be scheduled in a later microtask.
https://api.dart.dev/stable/2.15.1/dart-async/Future/then.html
So what happens is that:
print(1)
.Future.value(2)
is done in sync and the following .then
will be done in a microtask. The queue of microtasks is now: print(1)
, print(2)
.print(3)
. This gives the first line in your input..then()
. The queue of microtasks is now: print(1)
, print(2)
, print(4)
.After main()
is done we run the microtasks in order they come in which explains the rest of your output.
An important note is that you are never awaiting on any of the returned Future
from the .then()
methods so any async stuff will first be executed when main()
is done.
Upvotes: 5