In an async method where the code is not await
ing anything, is there a reason why someone would mark it async, await the task, and then return?
Besides the potential un-necessity of it, what are the negative ramifications of doing so?
For this example, please assume that QueryAsync<int>
returns Task<int>
.
private static async Task<int> InsertRecord_AsyncKeyword(SqlConnection openConnection)
{
int autoIncrementedReferralId =
await openConnection.QueryAsync<int>(@"
INSERT INTO...
SELECT CAST(SCOPE_IDENTITY() AS int)"
);
return autoIncrementedReferralId;
}
private static Task<int> InsertRecord_NoAsyncKeyword(SqlConnection openConnection)
{
Task<int> task =
openConnection.QueryAsync<int>(@"
INSERT INTO...
SELECT CAST(SCOPE_IDENTITY() AS int)"
);
return task;
}
// Top level method
using (SqlConnection connection = await DbConnectionFactory.GetOpenConsumerAppSqlConnectionAsync())
{
int result1 = await InsertRecord_NoAsyncKeyword(connection);
int result2 = await InsertRecord_AsyncKeyword(connection);
}
In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. Code after each await expression can be thought of as existing in a .then callback.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
Async/Await makes it easier to write promises. The keyword 'async' before a function makes the function return a promise, always. And the keyword await is used inside async functions, which makes the program wait until the Promise resolves.
Read this blog post from Stephen Cleary:
Eliding Async and Await
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With