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:
1. await lookUpVersion();
To use await, code must be in an async function—afunction marked as async:
1. Future checkVersion() async {
2. var version = await lookUpVersion();
3. // Do something with version
4. }
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:
1. try {
2. version = await lookUpVersion();
3. } catch (e) {
4. // React to inability to look up the version
5. }
You can use await multiple times in an async function.For example, the following code waits three timesfor the results of functions:
1. var entrypoint = await findEntrypoint();
2. var exitCode = await runExecutable(entrypoint, args);
3. 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:
1. Future main() async {
2. checkVersion();
3. print('In main: version is ${await lookUpVersion()}');
4. }
