Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Created November 22, 2018 14:14
Show Gist options
  • Save graphicbeacon/2aec97fbc738e4c3ec4cb0aae544b77b to your computer and use it in GitHub Desktop.
Save graphicbeacon/2aec97fbc738e4c3ec4cb0aae544b77b to your computer and use it in GitHub Desktop.
Sample code demonstrating Asynchronous programming with Futures
import 'dart:convert';
import 'dart:html';
import 'dart:async';
main() {
// Basic example
var result = Future(() => 'Hello World!');
print(result);
result.then((data) => print(data));
// Delayed example
var delayedResult = Future.delayed(Duration(seconds: 2), () => 'Displayed after 2 seconds');
delayedResult.then((result) => print(result));
// Error handling & Chainable methods
var showError = false;
Future(() => showError ? throw 'There was an error.' : '{"data": "Success!"}')
.then((data) => json.decode(data))
.then((result) => print(result['data']))
.catchError((error) => print(error));
// Dart library example
HttpRequest.getString('https://swapi.co/api/people/1')
.then(print)
.catchError((err) => print('There was a problem: $err'));
// Callback signatures in a Future context
lookupVersion(cb) => Timer(Duration(seconds: 2), () => cb('v2.1.0'));
lookupVersion((version) => print('Got the version: $version'));
Future lookupVersionAsFuture() {
var completer = Completer();
lookupVersion((version) => completer.complete('Got `Future` version: $version'));
// lookupVersion((_) => completer.completeError('There was a problem'));
return completer.future;
}
lookupVersionAsFuture()
.then((version) => print('Got the version as a Future result: $version'))
.catchError(print);
// Async/await
lookupVersionAsAsyncAwait() async {
var version = await lookupVersionAsFuture();
print('With async/await: $version');
}
lookupVersionAsAsyncAwait();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment