2021-12-20

How do async/await/then really work in Dart?

This is maybe a recurring question but I found conflicting answers and I'm now confused as to which of them is the correct one. I thought I understood the concept then I started reading all of those answers and got totally confused so I'm looking for a definite and simple answer to my question that I could easily comprehend.

As per this answer and this article, await is supposed to interrupt code execution and actually wait for the future to complete and then continue executing the rest of the code sequentially. It also suggests that this might block the main thread, which is only logical in that case.

On the other hand, this, this and this video from the flutter team suggest that await is not going to block the rest of code execution and that it's just syntactical sugar to register callbacks to be executed when the future finishes, which is the same thing that then does.

Now, I tried to write a small program to understand which of them is correct and it seems that the first approach is the way to go:

import 'dart:async';

// prints: 
// 1000+
// 1000+
void main() async {
  Stopwatch watch = Stopwatch();
  
  watch.start();
  
  await Future.delayed(Duration(seconds:1)).then((_){print(watch.elapsedMilliseconds);});
  
  print(watch.elapsedMilliseconds); 
  
}

In opposition to:

import 'dart:async';

// prints:
// 0
// 1000+
void main() async {
  Stopwatch watch = Stopwatch();
  
  watch.start();
  
  Future.delayed(Duration(seconds:1)).then((_){print(watch.elapsedMilliseconds);});
  
  print(watch.elapsedMilliseconds);
  
}

So I just want to know why the flutter team and some people are suggesting that await does not block the code execution and how this concept really works.



from Recent Questions - Stack Overflow https://ift.tt/3Fea7to
https://ift.tt/eA8V8J

No comments:

Post a Comment