await inside foreach possible?

3,773 views
Skip to first unread message

Benjamin Strauß

unread,
Apr 6, 2015, 1:27:49 PM4/6/15
to mi...@dartlang.org
Hi, i have an async function that looks like this:

Future<bool> clear() async
{
    int result = 1;

    _caches.forEach((Cache cache)
                    {
                        bool succeeded = await cache.clear();

                        result &= succeeded ? 1 : 0;
                    });

    return result == 1;
}

This throws an error because the closure itself is not marked as async. If i change it to this everything works inside dartium.

Future<bool> clear() async
{
    int result = 1;

    _caches.forEach((Cache cache) async
                    {
                        bool succeeded = await cache.clear();

                        result &= succeeded ? 1 : 0;
                    });

    return result == 1;
}

But is this safe to compile to javascript? Am i allowed to mark callbacks as async, even if the resulting future is not used in the underlying system? Is there a better way to do this?

Günter Zöchbauer

unread,
Apr 6, 2015, 1:38:45 PM4/6/15
to mi...@dartlang.org
This works fine. If it doesn't create a bug report.

Justin Fagnani

unread,
Apr 6, 2015, 1:41:32 PM4/6/15
to General Dart Discussion
You need to use Future.forEach: https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:async.Future#id_forEach

And you'll also need to await the forEach:

Future<bool> clear() async {
  var succeeded = true;
  await Future.forEach(_caches, (Cache cache) async {
    succeeded = succeeded && await cache.clear();
  });
  return succeeded;
}

By the way, your operation is an async fold on _caches. You can use Quiver's async.reduceAsync to make this shorter:

import 'package:quiver/async.dart' show reduceAsync;

Future<bool> clear() => reduceAsync(_caches, true, (s, cache) async => s && await cache.clear());

--
For other discussions, see https://groups.google.com/a/dartlang.org/
 
For HOWTO questions, visit http://stackoverflow.com/tags/dart
 
To file a bug report or feature request, go to http://www.dartbug.com/new

To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.

Benjamin Strauß

unread,
Apr 6, 2015, 2:18:27 PM4/6/15
to mi...@dartlang.org
Thank you, i already use quiver in my project, so i will just use the function. :)

Kevin Moore

unread,
Apr 7, 2015, 8:18:40 PM4/7/15
to mi...@dartlang.org
Future<bool> clear() async {
  int result = 1;
  for (var cache in _caches) {
    if (!await cache.clear()) {
      return false;
    }
  }
  return true;
}


Alex Tatumizer

unread,
Apr 7, 2015, 10:39:21 PM4/7/15
to mi...@dartlang.org
attempt of a parallel version (never tested):
Future<bool> clear() async {
 
var results = await Future.wait(_caches.map((c)=>c.clear()));
 
return results.fold(true, (acc, val)=> acc && val);
}

Reply all
Reply to author
Forward
0 new messages