1
votes

I think I understand the idea behind async, returning a Future, but I am not clear on how async behaves on a very basic level. From my understanding, it does not automatically create asynchronous behavior in a program. For example:

import 'dart:async';
main() {
  a();
  b();
}
a()  {
  new Timer(new Duration(milliseconds: 20), () {});  // create latency
  print("a");
}
b()  {
  print("b");
}
// a
// b

If you put async after the a(), the b() is executed first asynchronously, and a() executes after the given latency:

import 'dart:async';
main() {
  a();
  b();
}
a() **async** {
  new Timer(new Duration(milliseconds: 20), () {});  // create latency
  print("a");
}
b()  {
  print("b");
}
// b 
// a

But if you put async after both a() and b(), a() executes first, similar to not using async at all:

import 'dart:async';
main() {
a();
b();
}
a() **async** {
  new Timer(new Duration(milliseconds: 20), () {});  // create latency
  print("a");
}
b() **async** {
  print("b");
}
//a
//b

Is using async on all functions cancelling the async function completely?

Now, I think that the main() async does not actually activate the asynchronous behavior by itself. If you add async after the main(), nothing changes. However, it allows for you to use await, in case you must wait for the a() function to finish first, before you continue the program. Is this right?

import 'dart:async';
main() **async** {
  **await** a();
  b();
}
a() **async** {
new Timer(new Duration(milliseconds: 20), () {});  // create latency
print("a");
}
b() {
print("b");
}
// waits for the value of a() if you put **await** keyword
// a
// b

However, I see main() async {} alot as well as using it after the script html tag, yet there is no await anywhere. Does it mean different things in different contexts? I hope I have explained the logic adequately. Can you explain how I am misunderstanding the use of async/await? Thank you.

1

1 Answers

2
votes
a()  {
  new Timer(new Duration(milliseconds: 20), () {});  // create latency
  print("a");
}

This code doesn't delay execution of print("a"); for 20 ms. It just delays the execution of {} which is enqueued for later execution, and then immediately continued with print("a");

Your code using async / await and the equivalent code without async / await would look like:

import 'dart:async';
main() async {
  await a();
  b();

  await main2(); // call the example without async/await
}
Future a()  async {
  await new Future.delayed(const Duration(milliseconds: 20), () {});  // create latency
  print("a");
}
void b()  {
  print("b");
}

Future main2() {
  return a2().then((_) {
    b();
  }); 
}

// equivalent of a without async/await
Future a2()   {
  return new Future.delayed(const Duration(milliseconds: 20), () {})  // create latency
  .then((_) => print("a"));
}

Try on DartPad