user16746875
user16746875

Reputation:

Future assigned to MicroTask or Event Queue?

In the example below:

void main() {
  print('Start');
  Future(
    () {
      print('Mid');
    },
  );
  print('End');
}

Above, first Start prints, followed by End and then Mid. Mid is printed last due to the Future being pushed into the Event Queue to be processed through the Event Loop.

If the above is made into an async-await function, where the is Future awaited for:

void main() async {
  print('Start');
   await Future(
    () {
      print('Mid');
    },
  );
  print('End');
}

Start prints as usual, followed by Mid and then End.

In the second example, is Mid being printed second due to the Future being added to the MicroTask Queue to be executed quickly by the Event Loop, or is it still added onto the Event Queue to be executed by the Event Loop?

Upvotes: 1

Views: 402

Answers (1)

lrn
lrn

Reputation: 71623

The computation of Future(() { ... }) is scheduled in the event queue. It happens in a later event (a timer event, actually, not a microtask event).

That happens in both cases. Everything up to the scheduling of that computation is the same in both programs. It's what happens afterwards that differs.

In the first program, after the computation has been scheduled, the program goes on to print('End'); and main exits. At the later timer event, Mid is printed and the Future completes with null. Nobody listens to it, and the program ends.

In the second program, after the computation has been scheduled, the program awaits the resulting future. That means that then on that Future is called with a callback representing the continuation of the current function. Then the main method returns (a Future, since it's async) and exits.

When the timer event happens, the program prints Mid and then completes the first future with null. The callback added by the await gets invoked (maybe immediately, probably in the next microtask), which means that the rest of the async main function body executes, which prints End. Then the future returned by main is completed (with null). Since nobody listens to it, nothing else happens and the program exits.

The difference is not in when Mid is printed, but in when End is printed. In the second version, you wait for Mid to have been printed before continuing to print End.

Upvotes: 1

Related Questions