Steve Wash
Steve Wash

Reputation: 986

How do asynchronous GET requests work?

I THINK I understand the basic principle of an asynchronous POST method from a high level view point. The big advantage is that the caller gets a quick response, even though the processing of the data from the POST might not be completed yet.

But I don't really understand how this applies to a GET method. The response needs to contain the data, so how can there BE a response before processing is completed? Why have an API with a GET request handler that utilizes asynchronous methods?

I don't think it matters for this general type of question, but I'm writing in C# using Web API.

Upvotes: 3

Views: 999

Answers (3)

Lou Franco
Lou Franco

Reputation: 89192

So the app can do other things that don't need the data.

If you implement a GET as synchronous (and let's say you are on a bad network, where it takes 20 seconds to get it), you can't

  1. Show progress
  2. Allow the user to cancel
  3. Let them initiate other GETs
  4. Let them use other parts of the app

EDIT (see comments): The server wants to respond asynchronously for mostly the same reason (to give up the thread). Actually getting the data might be asynchronous and take some time -- you wouldn't want to block the thread for the whole time.

Upvotes: 1

usr
usr

Reputation: 171218

On the network there is no such thing as an async HTTP call. It's just data flowing over TCP. The server can't tell whether the client is internally sync or async.

the caller gets a quick response

Indeed, the server can send the response line and headers early and data late. But that has nothing to do with async IO or an async .NET server implementation. It's just some bytes arriving early and some late.

So there is no difference between GET and POST here.

why ... utilize asynchronous methods?

They can have scalability benefits for the client and/or the server. There is no difference at the HTTP level.

Upvotes: 3

Aaron Brager
Aaron Brager

Reputation: 66282

It doesn't make any sense if you're building a RESTful API, in which GET should return a resource (or a collection) and be idempotent (not make any changes).

But if you're not following those principles, a GET request could perform some work asynchronously. For example, GET /messages/3 could return the message to the client, but then asynchronously do other work like:

  • mark the message as read
  • send a push notification to the user's other clients indicating that the message is read
  • schedule a cronjob 30 days in the future to delete the message
  • etc.

None of these would be considered a RESTful API, but are still used from time to time.

Upvotes: 0

Related Questions