What is asynchronous support
Learn about asynchronous threads
- Why is there asynchronousness?
- Dart is a single-threaded language. When it encounters delayed operations (such as IO operations and delayed execution), the operations executed in the thread will be blocked, and the user will feel stuck. Therefore, asynchronous processing is usually used to solve the thread blocking problem.
- Dart single-threaded model
- Dart runs in a single thread using a message loop mechanism, which contains two task queues, one is the "microtask queue" microtask queue and the other is the "event queue" event queue.
- Dart thread running
- The Dart thread runs, and after the entry function main() is executed, the message loop mechanism is started.
- First, tasks in the micro-task queue will be executed one by one in first-in first-out order. After all micro-task queues are executed, tasks in the event queue will be executed. After the event task is executed, the micro-task will be executed, and this cycle will be repeated.
How to support asynchronous programming in Dart
- Asynchronous functions: Future and Stream
- Keywords
async
andawait
Asynchronous programming is also supported
Asynchronous processing using async and await
- Let’s take a look at a case first:
/*The return value is of the Future<String> type, that is, its return value is a String type value in the future*/ /*async keyword declares that there is code inside the function that needs to be executed delayed*/ getData() async { /*await keyword declares that the operation is delayed execution, and then the return operation result*/ return await "This is a doubi"; }
- Call this method and get the return value. The console actually reported an error
String data = getData();
- Reason for the error
- data is type String, and the function getData() is an asynchronous operation function whose return value is the result of await delay execution. In Dart, there is an operation with await tag, and the result values are all Future objects. Future is not a String type, so an error is reported.
- To summarize:
- When obtaining the asynchronous method, the return of await .. is actually a future object with delay calculation.
- Two points to note:
- Await keyword must be used inside the async function
- Calling async function must use the await keyword
What is Future
With JavaScript
Promise
Very similar, representing the final completion (or failure) of an asynchronous operation and its result value.-
It is used to handle asynchronous operations. If the asynchronous processing is successful, a successful operation will be performed. If the asynchronous processing fails, an error will be captured or subsequent operations will be stopped.
- Future means something that will happen in the future, and a value can be obtained from Future in the future. When a method returns a Future, two things happen:
- Queue something and return an unfinished Future
- After the work is finished, the state of Future will become completed, and the return value of this work can be obtained.
- Future means something that will happen in the future, and a value can be obtained from Future in the future. When a method returns a Future, two things happen:
-
Get the Future return value in two ways:
- Use async to match await
- Using the API provided by Future is actually to use Future's then method to get the return value
Future example
void doAsyncs() async{ //then catchError whenComplete new Future(() => futureTask()) // Functions of asynchronous tasks .then((m) => "1-:$m") // Subtask after task execution .then((m) => print('2-$m')) // where m is the result returned after the previous task is executed .then((_) => new ('3-:error')) .then((m) => print('4-')) .whenComplete(() => print('5-')) //Which is not executed at the end, it is usually put to the last callback .catchError((e) => print('6-catchError:' + e), test: (Object o) { print('7-:' + o); return true; // Return true and will be caught by catchError }) .then((_) => new ('11-:error')) .then((m) => print('10-')) .catchError((e) => print('8-:' + e)) ; } futureTask() { return (Duration(seconds: 5),() => "9-Walk to run"); }
- Execution results
I/flutter: 2-1-:9-Walk to run
I/flutter: 5-
I/flutter: 7-:3-:error
I/flutter: 6-catchError:3-:error
I/flutter: 8-:11-:error
Introduce Async/await
- In Dart
async/await
- and JavaScript
async/await
The functions and usage are the same.
- and JavaScript
async/await eliminates callback hell
- The code is as follows:
task() async { try{ String id = await login("alice","******"); String userInfo = await getUserInfo(id); await saveUserInfo(userInfo); //Perform the next operation } catch(e){ //Error handling print(e); } }
-
async
Used to indicate that the function is asynchronous- The defined function will return a
Future
Object, you can use the then method to add callback functions.
- The defined function will return a
-
await
Behind is oneFuture
- It means that the asynchronous task will be completed and will not go down after it is completed asynchronously;
await
Must appear inasync
inside the function.
- It means that the asynchronous task will be completed and will not go down after it is completed asynchronously;
What is Stream
-
Stream
Also used to receive asynchronous event data, andFuture
The difference is that it can receive the results of multiple asynchronous operations (success or failure). - When performing an asynchronous task, the result data or error exception can be passed by multiple triggering success or failure events.
Stream application example
-
Stream
It is often used in asynchronous task scenarios that read data multiple times, such as network content download, file reading and writing, etc.:
([ //Return the result after 1 second (new Duration(seconds: 1), () { return "hello 1"; }), // Throw an exception (new Duration(seconds: 2),(){ throw AssertionError("Error"); }), //Return the result after 3 seconds (new Duration(seconds: 3), () { return "hello 3"; }) ]).listen((data){ print(data); }, onError: (e){ print(); },onDone: (){ print("Finish"); });
- It will output in turn:
I/flutter (17666): hello 1
I/flutter (17666): Error
I/flutter (17666): hello 3
This is the end of this article about a brief analysis of the asynchronous processing of the Dart language. For more related Dart asynchronous processing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!