“This is the 17th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Introduction to the
Those familiar with javascript should know that ES6 has introduced await and async syntax to make it easy to program asynchronously and get rid of callback hell. As a nascent language, there is no reason why Dart should not inherit this quality. Naturally, DART also has await and async languages, so take a look.
Why asynchronous programming
So why asynchronous programming? Can’t synchronization alone solve this problem?
Synchronization is sufficient in most cases, but the synchronization scenario is flawed in the following cases.
- A situation where it takes a long time to download data from the network.
- The time taken to read the database.
- The condition in which data is read from a file.
In summary, asynchronous programming can be used if certain operations take a lot of time.
How to use
Async is a method descriptor, and if we want to use await, we must use async in conjunction with async:
Future<void> checkVersion() async {
var version = await lookUpVersion();
// Do something with version
}
Copy the code
Note that “await” is usually followed by a Future object.
Let’s take a look at an example of the wrong use of asynchronous programming:
String createOrderMessage() { var order = fetchUserOrder(); return 'Your order is: $order'; } Future<String> fetchUserOrder() => Future.delayed( const Duration(seconds: 2), () => 'Order one! ', a); void main() { print(createOrderMessage()); }Copy the code
The above code was supposed to print out the data that was taken time to retrieve from the database, but it didn’t work out that way because the fetchUserOrder method is an asynchronous method that doesn’t return immediately, causing the result to fail to print.
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()); }Copy the code
Future
We used the Future above with async and await. In Java, a Future represents the result of a thread’s execution. In DART, a Future represents the result of an asynchronous execution.
A Future has two states: uncompleted or completed.
When an asynchronous function is initially executed, an unfinished Future is returned. The unfinished Future will wait for asynchronous execution to complete or fail.
Whether an asynchronous program succeeds or fails, it eventually returns a complete state.
Async returns a Future that can be followed by a generic type, such as a Future that returns a string and a Future that returns no 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'));
}
Copy the code
Here is an example of an exception:
Future<void> fetchUserOrder() {
return Future.delayed(const Duration(seconds: 2),
() => throw Exception('Logout failed: user ID is invalid'));
}
Copy the code
Asynchronous exception handling
In async functions, we can catch an exception thrown by an async method with an await function:
try { print('Awaiting user order... '); var order = await fetchUserOrder(); } catch (err) { print('Caught error: $err'); }Copy the code
Call an asynchronous function within a synchronous function
FetchUserOrder (), described above, returns a Future that represents an asynchronously executed procedure.
So if it’s a synchronous method, like in main(), how do you call an asynchronous method and get the return value?
Await is definitely not ok because await can only be called in async methods. This is where the then statement is used:
fetchUserOrder().then(order=>'do something');
Copy the code
Then statements wait for the asynchronous execution to return the result, and then process the result, essentially the javascript equivalent of a callback.
conclusion
That’s how async and await are used in DART.
This article is available at www.flydean.com/12-dart-asy…
The most popular interpretation, the most profound dry goods, the most concise tutorial, many tips you didn’t know waiting for you to discover!
Welcome to pay attention to my public number: “procedures those things”, understand technology, more understand you!