Wecherowski
Wecherowski

Reputation: 958

Dart Lang: Avoid marking all functions with async

Dart newbie here, I'm currently learning about asynchronous execution in Dart. I'm a bit irritated about how concurrency works in Dart, take the following scenario from their codelab:

void printOrderMessage () async {
  try {
    var order = await fetchUserOrder();
    print('Awaiting user order...');
    print(order);
  } catch (err) {
    print('Caught error: $err');
  }
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex.
  var str = Future.delayed(Duration(seconds: 4), () => throw 'Cannot locate user order');
  return str;
}

Future<void> main() async {
  await printOrderMessage();
}

In this case, the asynchronous operation is fetching the the user order from say a DB. Now because of Dart's await / async mechanism, every function that is related to the async operation is required to have a Future<> return type and must be tagged with async.

This feels clunky ... Imagine if some value deep in my function chain is being calculated asynchronously, would I really need to always return a future? Is there some other construct to synchronize code in Dart than await? Or have I misunderstood the concept?

Upvotes: 2

Views: 751

Answers (1)

jamesdlin
jamesdlin

Reputation: 89985

If callers need to be able to wait for your asynchronous operation to finish, then your asynchronous function must return a Future that can be awaited. This is contagious; if callers of those callers need to be able to wait, then they too need to have Futures to wait upon.

If callers should not wait, then you can have a "fire-and-forget" function that does not need to return a Future:

Future<void> foo() {
  // ...
}

// Does not need to return a Future.  Consequently, callers cannot
// directly determine when `foo` completes.
void bar() {
  foo();
}

Upvotes: 7

Related Questions