Futures & Iterables in Dart
What happens if you need to loop over an iterable and perform a function that returns a future on each item?
If you aren't concerned about the order that the results are returned, you can use Future.wait and map the iterable like so:
Future<String> doSomething() {
var completer = new Completer();
List v = [];
v['something'] = 'something';
Future.wait(my_list.map((item) => item.itemFunc())).then((List results) {
v['results'] = results;
var str = JSON.encode(v);
completer.complete(str);
}).catchError((e) {
print('There was an error: $e');
completer.complete('');
});
return completer.future;
}
Written by Iain Campbell
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Dart
Authors
inuyasha82
3.51K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#