As a quick note without any explanation, this is a Dart async/wait/Future example:
import 'dart:async'; Future<int> async1(int delay) { return Future.delayed(Duration(milliseconds: delay)) .then((_) => 1); // '_' means "ignore this value, it’s not needed here" } void main() async { // this prints some time later, after 'E' Future.wait([async1(100), async1(1000)]) .then((List<int> nums) { nums.forEach((i) => print('i = $i')); }); print('A'); print('B'); // this forces the code to wait here. // 'await' means "wait right here". var x = await async1(100); //the code waits here before moving on print('x = $x'); print('C'); print('D'); print('E'); }
That Dart code prints the following output:
A B x = 1 C D E i = 1 i = 1
I based this example on another example I saw somewhere, but I can’t remember where I saw it. But for myself, I mostly wanted to share/remember the difference between Future/then and async/await in Dart.
A second Dart Future/then and async/await example
As a second Dart Future/then and async/await example, let’s change that code a little bit:
import 'dart:async';
Future<int> async1(int value) {
return Future.delayed(Duration(milliseconds: value))
.then((_) => value); // '_' means "ignore this value, it’s not needed here"
}
void main() async {
print('before future/then');
// this prints some time later, after 'E'
Future.wait([async1(1000), async1(500)])
.then((List<int> nums) {
nums.forEach((i) => print('Future::then, i = $i'));
});
print('after future/then; before await async');
// this forces the code to wait here.
// 'await' means "wait right here".
final x = await async1(750); //the code waits here before moving on
print('after await, x = $x');
print('the end');
}
Here I made these changes:
async1
uses the value it’s given as the wait time, and also prints that value- I changed the
print
statements in the code
In this case, the code prints the following output:
before future/then
after future/then; before await async
after await, x = 750
the end
Future::then, i = 1000
Future::then, i = 500
Once again you can see:
- The main thread of the code goes flying right through the
Future::then
code; unlike await/async, the thread doesn’t pause for Future/then - The code does wait for the
await
code before moving on - The end of the program is reached
- The Future/then code finally prints some time later
So again, the lesson is the same as before:
- The main thread does not pause for Future/then
- The main thread does pause for an
await
statement
Here I write the “main thread,” but since really just has one thread, that isn’t 100% correct, but if you’re used to Java/Scala/JVM programming languages, it’s easier to think of the Future/then code as running on another thread in parallel to the main thread.