csstudent1418
csstudent1418

Reputation: 329

Dart await Future.wait() with vs without inner async await

In Dart, given an async method

Future transformObject(T object);

both of the following are legal:

Future transformData(Iterable<T> objects) async {
    await Future.wait(objects.map((o) => transform(o));
}

and

Future transformData(Iterable<T> objects) async {
    await Future.wait(objects.map((o) async { await transform(o); });
}

Is there any difference betwen the two, what is it and which one should I go for if I just want to transform all data objects asynchronously?

Upvotes: 1

Views: 886

Answers (1)

lrn
lrn

Reputation: 71873

If transsform returns a Future, then there is no meaningful difference between transform, (o) => transform(o) and (o) async => await transform(o);. The more wrappings you add, the more overhead, but it's basically the same.

Your function, (o) async { await transform(o); } doesn't return the result of the future that transform returns, but if you don't need that value, then it shouldn't matter. (The name does suggest the you care about the value, though.) You'll still wait for that future to complete before being done.

What you could (possibly should) go for:

Future<List> transformData(Iterable<T> objects) =>
    Future.wait(objects.map(transform));

Upvotes: 2

Related Questions