user3356784
user3356784

Reputation: 47

Javascript asynchronous loop

Want to make a lot of asynchronous requests. The number of requests from 10 to 1000, should write down the answer in array (order is not important, no dependency)

   while (i<5) {
        api.get("get", offset: i, function(result) {
            datag = datag.concat(data.id);
        })
    i++;
    }

Is it right way? Is there a particular? the synchronous javascript used with asynchronous requests and i afraid of unexpected situations

Upvotes: 0

Views: 52

Answers (1)

user229044
user229044

Reputation: 239521

No, this is not the correct way. You are making the requests in parallel. It may work for 5 request, but for thousands, some will surely timeout.

You need to make each request trigger the next request in its success timeout:

var i = 0;

function success (result) {
   datag = datag.concat(result.id);

   // launch the next request
   if (++i < 5) {
     api.get("get", offset: i, success)
   }
}

// launch the first request
api.get("get", offset: i, success);

Upvotes: 1

Related Questions