Running this returns a string label that represents a future instance rather than the actual result. This happens because futures work in an asynchronous manner. We need to use the then method to capture the results once the computation is complete.
Here is another example that adds a delayed period of time before returning the result. Use the catchError method to handle exceptions.
You can also chain your success and error methods. We can chain as many then blocks as possible. To demonstrate that, let's create a variable called showError, which will be used to trigger the catchError method callback. Then let's modify the computed result with this variable.
In our first success handler, convert the result to a map object using the jsonDecode method in the Dart convert library. Dart libraries are also feature-rich with functions that return future objects. Here is an example using the HttpRequest getString method to make an API call.
This works as expected as long as a future is returned. For asynchronous functions that are not based on the Future API, we can use the Completer class to wrap it within a future context. To demonstrate, let's create a function that accepts a callback function to be triggered once an asynchronous operation is complete.
To wrap this function so that a future is returned, we can use the Completer class that comes from the Dart async library. Create a wrapper function with a return type set to future. Create a Completer object and return its future.
Before the return statement, run our lookUpVersion operation. In the callback function, we can resolve our future by invoking the complete method on our Completer object.
To trigger the catchError method call, use the completeError method. Future-based APIs can also be used with async/await syntax. To do that, let's create a function, marking it with the async keyword before the opening curly bracket. For any function returning a future, prepend the await keyword before invoking it. Let's invoke this function.
To handle exceptions, wrap your await calls in a try-catch statement. Then modify lookUpVersion as future to respond with an error. Let's run again. Let's pass this one more time. This concludes the lesson.