[share] verification of await keyword behaviour

I want to share how I verify the point: everything after await keyword is sent to event queue.
When I first come across the code in the book below:

Future<void> main() async {
  print('Before the future');

  
  final value = await Future<int>.delayed(
    Duration(seconds: 1),
    () => 42,
  );
  print('Value: $value');
  print('After the future');
}

It look like to me that the last two lines are synchronous also. The await keyword just stop the program temporarily and run the Future, then go back to run the last two lines.

Until the book tells me everything after the await keyword is sent to the event queue. I just want to verify this point. Therefore, I re-write the code as follows:

Future<void> main() async {
  print('Before the future');
  Future<int> futureFunction() {
    Future.microtask(
      () => print("put microtask queue"),
    );
    return Future.value(42);
  }
  final value = await futureFunction();
  print('Value: $value');
  print('After the future');
}

The print output put microtask queue exists before the last 2 print lines. Now, I am convinced the last two lines are also in event queue. This is because if the last two line is synchronous, they will have higher priority than the microtask queue. Then, the microtask print output should be at last.

2 Likes

Just to make sure, you’re confirming that what the book says is true, right? Good job on putting it to the test.

2 Likes

Yes, I just want to confirm what the book says is true. Thank you for your explanation in the book.
If I encounter this in my project, I probably will not think how it work as long as the code “works” for me.
Really I think deeper and have a clearer understanding.

2 Likes

Thank you @ellery for applying what you learned in the book and contributing to the forum. Keep up the great work! Your participation is valued, and we look forward to more of your insights. Happy learning!

Thank you, @suragch , for your prompt and helpful response to the question. Your expertise and assistance are greatly appreciated!