Dart asynchronous function Async, await, Future related understanding

foreword

Because the Dart language is a single-threaded model, it is not possible to use the multi-threaded feature to open a sub-thread like Java, and perform time-consuming operations in the sub-thread. Therefore, we need to perform time-consuming operations in an asynchronous manner, such as network requests, database operations, file reading and writing, etc.

example

First, add dependencies to the pubspec.yaml file

dependencies:
  http: ^0.13.5

Then, create a new dart file to try how to use asynchronous operations. We define a private method startMethod() and mark it as async, indicating that this is an asynchronous method. In this method, 3 statements are printed and a getHttp( )method.

The getHttp() method is also an asynchronous method, and it performs a time-consuming operation (network request) and returns a string. At this time, you may have doubts, why the return value of the method is Future, but I can also return a string? Don't worry, just read on.

import 'package:http/http.dart' as http;

main(){
  _startMethod();
  print("C start");
}

Future _startMethod() async{
  print('A start');
  print(await getHttp());
  print('A end');
}
Future getHttp() async{
  final result = await http.get(Uri.https('jianshu.com'));
  return 'result :${result.headers}';
}

Run the main method, and the return value obtained is as follows:

A start
C start
result :{...}
A end

The program runs in order, and there is no problem with printing the first line, but why does the second line directly print C start? This is the function of the asynchronous method in the Dart language.

In the async method, the statements before the await are executed normally, and the methods after the await are all waited, and the code after the await (request http) is executed, and the following code is not continued until the result is returned.

And when encountering await, the method (_startMethod) will immediately return a Future, without affecting the execution of the upper layer call (print C start)

tips

In fact, the use of a Future is omitted here. In fact, Future will be followed by a generic type, representing what type of result this function will return in the future.

Not omitted version:

import 'package:http/http.dart' as http;

main(){
  _startMethod();
  print("C start");
}

Future<void> _startMethod() async{
  print('A start');
  print(await getHttp());
  print('A end');
}
Future<String> getHttp() async{
  final result = await http.get(Uri.https('jianshu.com'));
  return 'result :${result.headers}';
}

grammar

Working with futures: async and await

The async and await keywords provide a declarative way to define asynchronous functions and use their results. Remember these two basic guidelines when using async and await:

  • To define an async function, add async before the function body:
  • The await keyword works only in async functions. 

When defining an asynchronous function, async must precede the function body

The await keyword must be used in an asynchronous function to be useful

Advanced

Next, we add two lines of printing to the getHttp() method, and then check the running results

import 'package:http/http.dart' as http;

main(){
  _startMethod();
  print("C start");
}

Future _startMethod() async{
  print('A start');
  print(await getHttp());
  print('A end');
}
Future getHttp() async{
  print('B http start');
  final result = await http.get(Uri.https('jianshu.com'));
  print('B http end');
  return 'result :${result.headers}';
}

The result is as follows:

A start
B http start
C start
B http end
result :{...}
A end

When you first see this result, you may be a little bit overwhelmed. This is actually a recursive idea, and it is easy to understand if we follow the rules step by step.

The program is executed in order, first print  A start  and then execute print(await getHttp()), and the _startMethod method starts to wait.

Then print  b http start , continue to execute the http.get method, and getHttp starts to wait. Because http.get has not been executed, a Future is returned to _startMethod. Similarly, print(await getHttp()) is not finished, _startMethod returns a Future, and the main method executes C start synchronously.

After http.get is executed, continue to execute  B http end, print result, and A end.

reference

Asynchronous programming: futures, async, await | Dart

Async, await, and Future features in Dart - Brief Book

Guess you like

Origin blog.csdn.net/TDSSS/article/details/129055921