Be happy
Be happy

Reputation: 121

Please explain the behaviour of Futures in dart here

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

Answers (1)

julemand101
julemand101

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:

  1. You schedule a microtask to call print(1).
  2. 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).
  3. The third line is sync and runs immediately in full so we run print(3). This gives the first line in your input.
  4. We schedule a new microtask because of the .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

Related Questions