Using async returns one item instead of multiple

Viewed 62

I'm using an ASP.NET 6 Core MVC web app.

I've been migrating from Webforms to MVC so a little rusty in some areas.

I'm trying to understand async and await usage (gone through a few tutorials and although it makes some sense, I need to tinker around with it a little).

I have some code written which is not async and decided to try to change it over.

public async Task<IActionResult> Index()
{
    var results = await collection.FindAsync(_ => true);

    foreach (var item in results.ToList())
    {
        await Response.WriteAsJsonAsync(item);
    }

    return View();
}

So without using async and await, I get a list of items but when using the above code only the first element is shown in the browser.

Is it possible to use async in this manner or am i missing something to get this working this way?

Edit (code that display all items in the list without async)

public IActionResult Index()
{
    var results = collection.Find(_ => true);

    foreach (var item in results.ToList())
    {
        Response.WriteAsync(item);
    }

    return View();
}
1 Answers

As you are already using an async method for appending to the response in your current code without awaiting it (which is a bad idea btw) the async Index()-Method should look something like this:

public async Task<IActionResult> Index()
{
    var results = await collection.FindAsync(_ => true);

    foreach (var item in results.ToList())
    {
        await Response.WriteAsync(item);
    }

    return View();
}

using WriteAsJsonAsync serializes whatever object you throw into it to json and sets the whole response Body - it doesn't append.

So the issue here doesn't lie within the switch to async but rather the used method.

Related