How to perform Ajax requests, a few at a time

后端 未结 3 713
余生分开走
余生分开走 2020-12-19 06:02

I am not really sure it is possible in JavaScript, so I thought I\'d ask. :)

Say we have 100 requests to be done and want to speed things up.

What I was thin

相关标签:
3条回答
  • 2020-12-19 06:23

    Yes, I have done something similar to this before. The basic process is:

    1. Create a stack to store your jobs (requests, in this case).
    2. Start out by executing 3 or 4 of the requests.
    3. In the callback of the request, pop the next job out of the stack and execute it (giving it the same callback).
    0 讨论(0)
  • 2020-12-19 06:28

    It's actually slower to break up 100 requests and batch post them 5 at a time whilst waiting for them to complete till you send the next batch. You might be better off simply sending 100 requests, remember JavaScript is single threaded so it can only resolve 1 response at a time anyways.

    A better way is set up a batch request service that accepts something like:

    /ajax_batch?req1=/some/request.json&req2=/other/request.json
    

    And so on. Basically you send multiple requests in a single HTTP request. The response of such a request would look like:

    [
       {"reqName":"req1","data":{}},
       {"reqName":"req2","data":{}}
    ]
    

    Your ajax_batch service would resolve each request and send back the results in proper order. Client side, you keep track of what you sent and what you expect, so you can match up the results to the correct requests. Downside, it takes quite some coding.

    The speed gain would come entirely from a massive reduction of HTTP requests. There's a limit on how many requests you send because the url length has a limit iirc.

    DWR does exactly that afaik.

    0 讨论(0)
  • 2020-12-19 06:35

    I'd say, the comment from Dancrumb is the "answer" to this question, but anyway...

    Current browsers do limit HTTP requests, so you can even easily just start all 100 request immediately, and the browser will take care of sending those requests as fast as possible, but limited to a decent number of parallel requests.

    So, just start them all immediately and trust on the browser.

    However, this may change in the future (the number of parallel requests that a browser sends increases as end-user internet bandwidth increases and technology advances).

    EDIT: you should also think and read about the meaning of "asynchronous" in a javascript context.. asynchronous here just means that you give up control about something to some other part of a system. so "sending" an async request just means, that you tell the browser to do so! you do not control the browser, you just tell it to send that request and please notify me about the outcome.

    0 讨论(0)
提交回复
热议问题