What is a Future?
Futures are used to store the results of asynchronous processes. As mentioned in Part One, asynchronous operations can result in Success (often with data) and Failure (often with error data). A Future will store the data from the Success.
Lets Run Some Code
Go to your web-browser and navigate here: https://dartpad.dartlang.org. Paste the following code into the code area on the left-side:
import 'dart:async';
String createLongString(int count){
print('start count up');
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
sb.write(" ${i}");
}
print('finish count up');
return sb.toString();
}
Future createFutureCounter(int count) {
return new Future(() { return createLongString(count); });
}
void main() {
print('start main');
Future future = createFutureCounter(100);
print('adding Future API callbacks');
future.then((value) => handleCompletion(value)).catchError((error) => handleError(error));
print('finish main');
}
void handleError(err){
print('Async operation errored: ${err}');
}
void handleCompletion(value){
print('Async operation succeeded: ${value}');
}
Now hit the blue 'Run' button at the top and the following results should appear on the right side:
start main
adding Future API callbacks
finish main
start count up
finish count up
Async operation succeeded: 0 1 2 3 4 5 6 7 8 9 10 .... 99
What Happens When You Run the Code
- The ‘main’ method is short-lived. It calls ‘createFutureCounter’, is returned a future, adds a callback to the future and finishes. It finishes almost immediately, that means that it was not blocked by invocation of heavy synchronous code.
- The ‘createFutureCounter’ method is called by the main and returns a new Future object containing a lambda which is executed asynchronously, calling the ‘countUp’ method.
- The ‘countUp’ method then does the relatively slow work of counting up the numbers asynchronously.
- Once the ‘count up’ completes then the callback (the one that was added in the ‘main’ method) is fired and we see ‘Async operation succeeded’.
Error Handling
If you are invoking an asynchronous process you need to handle errors that occur inside the asynchronous process. Lets simulate one by replacing the code in the method 'createLongString' with the following:
String createLongString(int count){
throw new Exception("a strange error occurred");
return "";
}
Now hit the blue 'Run' button at the top and the following results should appear on the right side:
start main
adding Future API callbacks
finish main
Async operation errored: Exception: an error
What Happens When You Run the Code
- The ‘createLongString’ method throws an Exception.
- The ‘createLongString’ never completes.
- The 'onError' asynchronous error handler is invoked with the error, which invokes the 'handleError' method with the error.
- The 'handleError' method prints ‘Async operation errored’.
Enough for the moment. Next week more code, including the async and await keywords.