0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.