Nested async & await in Web API application

Solution for Nested async & await in Web API application
is Given Below:

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);
    }

I want to build asynchronous Web API Using .NET Core

Why?

There are a number of incorrect answers to that question; the most common one is probably “to make it faster”. “To make it more scalable” I would say is only semi-correct.

The correct answer is “I have asynchronous work do to”, where “asynchronous” in this context is roughly the same as “I/O-bound”.

In your example code, you want an asynchronous Web API call because that call queries/updates the database.

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?

Once you have the correct reasoning around “why”, the solution is clearer. Specifically, you want to have asynchronous database methods first, and then make your API method asynchronous if it calls them.

Generally, it’s best to start at the lowest-level calls and make those use await. FirstOrDefaultAsync, AnyAsync, SaveChangesAsync, etc. Anything doing I/O can be changed to use await. Once GetUser is an asynchronous method (and should be called GetUserAsync), then make your GetUser action method use async/await.