Search code examples
dartdart-async

Dart Asynchronous Execution


import 'dart:io';
import 'dart:async';

void printDailyNewsDigest() {
  File file = new File("dailyNewsDigest.txt");
  Future future = file.readAsString();
  future.then((content) {
    print(content);
  });
}

void main() {
  printDailyNewsDigest();
  printWinningLotteryNumbers();//does something synchronous
  printWeatherForecast();//does something synchronous
  printBaseballScore();//does something synchronous
}

I have a simple question about asynchronous operations in Dart and specifically asynchronous operations in the above code. When does asynchronous execution begin in the above code? Does asynchronous execution begin with the file.readAsString() call or does it begin when main exits and the task queue is processed? The documentation that I read is a little vague about this one point.

If I had to guess, I would guess asynchronous execution would begin with the call to file.readAsString(). Am I right?


Solution

  • It begins when main() the 'current thread of synchronous execution' is finished.
    A part of readAsString is executed synchrounously but because it returns a Future it is obvious that somewhere inside readAsString some async operation was invoked. This means that it is scheduled for later execution. When main is finished the event queue is processed and the next scheduled async operation is executed.