ArtS
ArtS

Reputation: 2012

Is there a difference whether using await with return in Dart?

In my flutter project, say there's a foo(int x) async function. And bar() async that looks like:

Future bar() async {
  return foo(3);
}

The bar() function is just a simple capsule for foo(int x) with a certain parameter. And bar() is used as the future in a FutureBuilder.

I'm not sure if I should use await with return. I can't find related documentations online. So what's the difference between return foo(3) and return await foo(3)? Thank you!

Upvotes: 8

Views: 1797

Answers (3)

Konstantin Kozirev
Konstantin Kozirev

Reputation: 1262

Using this simple example you can see in which order prints yield:

Future<void> fetchUserOrder() {
  return Future.delayed(const Duration(seconds: 2), () => print('Large Latte'));
}

void main() async {
  await fetchUserOrder();
  print('Fetching user order...');
}

fetchUserOrder() returns Future. So if we call it in main with await, it will receive the Future, execute it and await for the result. Only then proceed to the second print of the main.

We could've written the fetchUserOrder() in such a fashion:

Future<void> fetchUserOrder() async {
  return await Future.delayed(const Duration(seconds: 2), () => print('Large Latte'));
}

And it wouldn't have had changed the result. It would work the same, the only difference is shorter code and that now you understand how it works.

Use https://dartpad.dev/ to launch these examples.

Upvotes: 0

user12492341
user12492341

Reputation:

No difference whatsoever.

Technically, using await first might wait for the Future to resolve before returning from the function, but you won't be able to tell the difference.

A Future is returned either way.

The async there is useless too, it might as well just be an arrow:

Future bar() => foo(3);

If it were not the last statement, and a return statement, this could matter, as pointed out in the comments, take the following:

Future bar() async {
    try {
        return await foo(3);
    } catch(error) {
        return baz;
    }
}

If foo rejects, then it matters quite a lot, as it would be handled by the callee, not the caller.

Upvotes: 13

Tensky
Tensky

Reputation: 99

Since you are returning Future, in this exact case, even if you don`t await it, the foo(3) will return Future instead and it is the exact thing your function wants to return. and if u await it there, then it will await in the function and then return the value.

you don`t even need await in this case if foo return Future. Then the caller of bar will instead await the bar.

Upvotes: 1

Related Questions