The author | | vlad source vlad (public number: fulade_me)
asynchronous
The Dart code base has a large number of functions that return Future or Stream objects. These functions are asynchronous, and they return before time-consuming operations have completed rather than waiting for time-consuming operations to complete. The async and await keywords are used to implement asynchronous programming and make your code look synchronous.
Future
You can obtain the result of a Future execution in two ways:
- use
async
andawait
; - use
Future API
;
Code that uses async and await is asynchronous, but looks a bit like synchronous code. For example, the following code uses await to wait for the execution result of an asynchronous function.
await lookUpVersion();
Copy the code
We must use await in asynchronous functions with the async keyword:
Future checkVersion() async {
var version = await lookUpVersion();
// Use version to continue processing logic
}
Copy the code
While an asynchronous function can handle time-consuming operations, it does not wait for these time-consuming operations to complete. An asynchronous function executes and returns a Future object when it encounters the first await expression, and then waits for the await expression to complete.
Use try, catch, and finally to handle exceptions caused by using await:
try {
version = await lookUpVersion();
} catch (e) {
// What happens when the version cannot be found
}
Copy the code
You can use the await keyword multiple times in asynchronous functions. For example, the following code waits for the result of a function three times:
var entrypoint = await findEntrypoint();
var exitCode = await runExecutable(entrypoint, args);
await flushThenExit(exitCode);
Copy the code
The return value of an await expression is usually a Future object; If not, it will automatically wrap it in a Future object. The Future object represents a “promise” and await expression blocks until the desired object returns.
If using await results in a compile error, make sure await is used in an asynchronous function. For example, if you want to use await in the main() function, the main() function must be identified with the async keyword.
Future main() async {
checkVersion();
print('executed in Main: the version is${await lookUpVersion()}');
}
Copy the code
Declaring asynchronous functions
To define an asynchronous function, simply add the async keyword to a normal method. Add the keyword async to the function and have it return a Future object. Suppose there are methods that return String:
String lookUpVersion() => '1.0.0';
Copy the code
Change it to an asynchronous function that returns Future:
Future<String> lookUpVersion() async= >'1.0.0';
Copy the code
Note that the function body does not need to use the Future API. Dart creates Future objects if necessary. If the function does not return a valid value, set its return type to Future
.
Stream
A Stream is also used to receive asynchronous event data and, unlike a Future, can receive the results (success or failure) of multiple asynchronous operations. That is, success or failure events can be fired multiple times to pass result data or error exceptions while performing an asynchronous task. Stream is commonly used in asynchronous task scenarios where data is read multiple times, such as network content download and file read and write. Here’s an example:
Stream.fromFutures([
// Return the result after 1 second
Future.delayed(new Duration(seconds: 1), () {
return "hello 1";
}),
// Throw an exception
Future.delayed(new Duration(seconds: 2), () {throw AssertionError("Error");
}),
// The result is returned after 3 seconds
Future.delayed(new Duration(seconds: 3), () {
return "hello 3";
})
]).listen((data){
print(data);
}, onError: (e){
print(e.message);
},onDone: (){
});
Copy the code
The above code in turn prints:
hello 1
Error
hello 3
Copy the code