Mehdi
Mehdi

Reputation: 598

Possible to get response of each API calls inside ForEach without waiting to end of loop?

I need to return response of each API call inside ForEach loop without waiting for end of it.

First Api to get data from SharePoint and call another Api to update website database:

[HttpGet]
[Route("GetAllFaqs")]
public async Task<ApiResult<List<FaqModel>>> GetAllFaqs()
{
    ApiSuccessResult<List<FaqModel>> faqs = await sharepointConnector.GetAllFaqsAsync();

    foreach (var faq in faqs.Response)
    {
        // Here I want to return response of this Api call 
        // so I could show on client side one by one
        await UpdateFaq(faq); 
    }

    return faqs;
}

Another Api to update website database:

[HttpPost]
[Route("UpdateFaq")]
public async Task<ApiResult<FaqSyncResult>> UpdateFaq(FaqModel model)
{
    ApiSuccessResult<FaqSyncResult> result = await websiteConnector.SyncFaq(model);

    return result;
}

Is it possible to return response inside ForEach loop without stop it and also without waiting for the end?

Upvotes: 0

Views: 589

Answers (1)

Stefan
Stefan

Reputation: 17668

This is usually not how it works.

There are 2 things which prevents you for doing this approach:

  • most javascript libraries used to fetch the data awaits the full response from the api
  • most javascript libraries used to process the data works with a full set of data

An alternative approach, to get this behaviour would be to push the data from the server to the client using HTTP2/websockets or SignalR.

I've implemented the SignalR variant quite a few times and it works really well. Here is an example on of chat application

The way it works, is basically sending data by a hub to the client (which is connected through the SignalR library) and call a piece of javascript with the appropriate data client side.

I must warn you however, this will break the "general-purpose" idea of the API because it relies heavily on a client accepting the data in this way.

Upvotes: 2

Related Questions