0
votes

As I understand it, you can await a future in Dart which blocks the currently executing async function until the future returns a result.

This for instance calling inSequence() takes three second to print its output.

// Return a String after a one second delay. No surprises here.
Future<String> long() async {
  await Future.delayed(Duration(seconds: 1));
  return ":)";
}


void inSequence() async {
  // sequentially wait on the futures - takes 3 seconds
  print(await long());
  print(await long());
  print(await long());
}

Alternatively if you want to run all Futures at once you can call Future.wait([...]). Then all the futures will execute and the result will be available once ready on any subsequent calls to async, so inParallel() below will only take one second to execute.

void inParallel() async {
  var f1 = long();
  var f2 = long();
  var f3 = long();
  
  Future.wait([f1,f2,f3]); // wait on all futures in parallel.
  
  print(await f1);
  print(await f2);
  print(await f3);
}

Everything above makes sense to me. However looking below to confusing() the code does not behave as I would expect. I would expect that this function takes three seconds to execute as each await is awaited before the string is printed, then moving on to the next until the function completes three seconds later. In actuality this function only takes 1 second and prints all results at once. Why? How is this working?

void confusing() async {
  var f1 = long();
  var f2 = long();
  var f3 = long();
  
  print(await f1);
  print(await f2);
  print(await f3);
}

Thanks.

I am not sure about the details in dart, but I think the difference is the time you start those async functions. In inSequence you await the first call to fullfill ilts future and return before you start the next. In confusing you still start all of them in parallel.lupz