Introduction

Friends who are familiar with javascript should know that the introduction of await and async syntax in ES6 can facilitate asynchronous programming and get rid of callback hell. As a new language, dart has no reason not to inherit this excellent quality. Naturally, there are await and async languages in dart, let's take a look.

Why use asynchronous programming

So why use asynchronous programming? Can't it be solved only by synchronization?

In fact, synchronization is sufficient in most cases, but in the following cases, the synchronization scene is still flawed.

  1. It takes a long time to download data from the Internet.
  2. The time-consuming situation of reading the database.
  3. The case of reading data from a file.

In summary, if certain operations take a lot of time, then asynchronous programming can be used.

how to use

Async is the method descriptor. If you want to use await, you must use it with async:

Future<void> checkVersion() async {
  var version = await lookUpVersion();
  // Do something with version
}
Note that the Future object is usually followed by await.

Let's look at an example of incorrectly using asynchronous programming:


String createOrderMessage() {
  var order = fetchUserOrder();
  return 'Your order is: $order';
}

Future<String> fetchUserOrder() =>
    Future.delayed(
      const Duration(seconds: 2),
      () => 'Order one!',
    );

void main() {
  print(createOrderMessage());
}

The above code is intended to print out the time-consuming data fetched from the database, but the result is not as expected. The reason is that the fetchUserOrder method is an asynchronous method, so it will not return immediately, which causes the printing of the result to fail.

Rewrite the above code with async:

Future<String> createOrderMessage() async {
  var order = await fetchUserOrder();
  return 'Your order is: $order';
}

Future<String> fetchUserOrder() =>
    Future.delayed(
      const Duration(seconds: 2),
      () => 'Large Latte',
    );

Future<void> main() async {
  print('Fetching user order...');
  print(await createOrderMessage());
}

Future

Above we used Future in the process of using async and await. In Java, Future represents the execution result of the thread. Future in dart represents the result of an asynchronous execution.

Future has two states: uncompleted or completed.

When an asynchronous function is first executed, an unfinished Future will be returned. This unfinished Future will wait for the completion or failure of the asynchronous execution.

Regardless of whether the asynchronous program succeeds or fails, it will eventually return a completion status.

The Future returned by async can be connected to the generic type to indicate the specific type returned. For example, Future<String> means returning a string, and Future<void> means not returning any value.

Here are two examples of different returns:

Future<String> fetchUserOrder() {
  return Future.delayed(const Duration(seconds: 2), () => 'Large Latte');
}

Future<void> fetchUserOrder() {
  return Future.delayed(const Duration(seconds: 2), () => print('Large Latte'));
}

The following is an exception example:

Future<void> fetchUserOrder() {
  return Future.delayed(const Duration(seconds: 2),
      () => throw Exception('Logout failed: user ID is invalid'));
}

Asynchronous exception handling

In the async function, the exception thrown in the await asynchronous method can be directly caught by try catch:

try {
  print('Awaiting user order...');
  var order = await fetchUserOrder();
} catch (err) {
  print('Caught error: $err');
}

Call an asynchronous function in a synchronous function

The fetchUserOrder() described above returns a Future<String>, which represents an asynchronous execution process.

So if it is a synchronous method, such as the main() function, how to call the asynchronous method and get the return value?

Await definitely won't work, because await can only be called in async methods. At this time, the then statement can be used:

fetchUserOrder().then(order=>'do something');

The then statement will wait for the asynchronous execution to return the result, and then process the result, which is actually equivalent to a callback in javascript.

Summarize

The above is the usage of async and await in dart.

This article has been included in http://www.flydean.com/12-dart-async/

The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!

Welcome to pay attention to my official account: "Program those things", know technology, know you better!


flydean
890 声望433 粉丝

欢迎访问我的个人网站:www.flydean.com