Handling Futures
When you need the result of a completed Future,you have two options:
- Use
asyncandawait. - Use the Future API, as describedin the library tour.
Code that uses async and await is asynchronous,but it looks a lot like synchronous code.For example, here’s some code that uses awaitto wait for the result of an asynchronous function:
await lookUpVersion();
To use await, code must be in an async function—afunction marked as async:
- Future checkVersion() async {
- var version = await lookUpVersion();
- // Do something with version
- }
Note: Although an async function might perform time-consuming operations, it doesn’t wait for those operations. Instead, the async function executes only until it encounters its first await expression (details). Then it returns a Future object, resuming execution only after the await expression completes.
Use try, catch, and finally to handle errors and cleanup in code that usesawait:
try {version = await lookUpVersion();} catch (e) {// React to inability to look up the version}
You can use await multiple times in an async function.For example, the following code waits three timesfor the results of functions:
var entrypoint = await findEntrypoint();var exitCode = await runExecutable(entrypoint, args);await flushThenExit(exitCode);
In await expression,the value of expression is usually a Future;if it isn’t, then the value is automatically wrapped in a Future.This Future object indicates a promise to return an object.The value of await expression is that returned object.The await expression makes execution pause until that object is available.
If you get a compile-time error when using await,make sure await is in an async function.For example, to use await in your app’s main() function,the body of main() must be marked as async:
- Future main() async {
- checkVersion();
- print('In main: version is ${await lookUpVersion()}');
- }