my linter is telling me this await
is unnecessary:
Unnecessary await keyword in return.
I thought if you're calling a function inside an async function and you want to get/return the value, rather than the future you had to use await
to designate you want the value, not the future.
Am I missing something here?
CodePudding user response:
As the documentation for that recommendation points out, you can take off the async
and just return the Future
, rather than using await
:
Future<Dictionary> get _localDir => getApplicationDocumentsDirectory();
This is called "eliding async/await". Stephen Cleary wrote an article about it (written for C#, but largely applicable for any language that uses async
and await
), which you may find helpful: Eliding Async and Await
In short, it's more efficient to do this in situations when you can:
By not including these keywords, the compiler can skip generating the async state machine. This means that there are fewer compiler-generated types in your assembly, less pressure on the garbage collector, and fewer CPU instructions to execute.
CodePudding user response:
In an async function, you do not need to use the await keyword if the value you want to return is not a Future. If the value is a Future, then you must use await to unwrap the value before returning it.
Here is an example:
Future<int> add(int a, int b) async {
return a b;
}
In this example, the add function is marked as async, which means that it returns a Future. Inside the function, we return the result of adding a and b, which is not a Future, so we do not need to use await. The Future returned by the add function will be completed with the result of adding a and b.
If the add function returned a Future, then we would need to use await to unwrap the value before returning it. Here is an example:
Future<int> add(int a, int b) async {
Future<int> result = someAsyncOperation();
return await result;
}
In this example, the add function is marked as async, which means that it returns a Future. Inside the function, we call the someAsyncOperation function, which returns a Future. We then use the await keyword to wait for the result of the Future returned by someAsyncOperation, and return the result. The Future returned by the add function will be completed with the result of someAsyncOperation.
I hope this helps!