Dart series: asynchronous programming in dart

brief introduction

Friends familiar with javascript should know that the syntax of await and async has been introduced into ES6, which can facilitate asynchronous programming and get rid of the 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 have a look.

Why asynchronous programming

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

In fact, in most cases, synchronization is enough, but in the following cases, the synchronization scenario is still flawed.

  1. It takes a long time to download data from the network.
  2. How long it takes to read the database.
  3. Reading data from a file.

In conclusion, if some operations take a lot of time, asynchronous programming can be used.

How do you use it?

Async is the descriptor of the method. If await is to be used, it must be used together with async:

Future<void> checkVersion() async {
  var version = await lookUpVersion();
  // Do something with version
}

Note that await is usually followed by a Future object.

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

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 retrieved 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, resulting in the failure of printing the result.

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 a thread. In dart, Future represents the result of an asynchronous execution.

Future has two states: incomplete or completed.

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

Whether the asynchronous program succeeds or fails, it will eventually return a completion status.

The Future returned by async can be generic, indicating the specific type to be returned. For example, Future < string > means to return a string, while Future < void > means not to return any value.

Here are two different return examples:

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 example of an exception:

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, you can directly use try catch to catch exceptions thrown in the asynchronous method of await:

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

Calling asynchronous functions in synchronous functions

The fetchUserOrder() described above returns a future < string >, indicating 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 is definitely not acceptable, because await can only be invoked in async's method. The then statement can be used at this time:

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

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

summary

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 find!

Welcome to my official account: "those things in procedure", understand technology, know you better!

Tags: Flutter dart

Posted on Sun, 21 Nov 2021 04:22:47 -0500 by PoOP