I want to build asynchronous Web API using .NET Core
If I have async Task that's awaiting for a result from the service as below
[HttpGet("User/")]
public async Task<IActionResult> GetUser()
{
var result = await _service.GetUser();
return Ok(result);
}
Now in _service.GetUser we do more than one task such as querying the database more than once.
So my question is do we have to use async & await as well in _service.GetUser, or is it enough that the caller method do? I'm kind of confused.
public async Task<UserResponseDTO> GetUser(UserRequestDTO userRequestDTO)
{
var userId = await _utilities.getUserId(); //shall we use it?
var user = await _dbContext.getFullUserInfo //shall we use it?
.Where(P => P.userId == userId).FirstOrDefault();
if (!string.IsNullOrEmpty(userRequestDTO.email))
{
var emailExists = await _dbContext.getFullUserInfo.Where(p =>
p.Email == userRequestDTO.email).AnyAsync(); //shall we use it?
}
await _dbContext.SaveChangesAsync();
return _mapper.Map<UserResponseDTO>(user);
}
GetUserasync and await the async calls in it. Although I don't think you need theSaveChangesAsyncas it does not appear that you actually change anything.await? Obviously it's possible (asynchronous programming was done beforeawaitwas even added to the language) butawaitwas specifically added because it's much easier than the alternative. If you just removed theawaitkeyword and did nothing else then of course the whole thing wouldn't even compile, so you need to do something.awaitinside a routine depended on the caller of the routine. How can you know if your caller is using it? And even if you did somehow know that, both awaiting a task immediately and storing it to be awaited later are valid techniques, how would you distinguish between them?