G
G
Grigory Vasilkov2017-04-25 14:24:45
JavaScript
Grigory Vasilkov, 2017-04-25 14:24:45

How to make a chain of dozens of requests without recursion?

The task is to make 10 requests run, when they are all - another 10, when they are all - another 10, etc.

while (data.length) {
    var slice = data.splice(0, 10);
    
    var ds = [];
    slice.forEach(function (v) {
      ds.push($.ajax({
        'url': 'index.php?action=getzip'
        'type': 'POST',
        'data': {
          'country': v.country,
          'city': v.city,
        },
        'dataType': 'JSON',
      }));
    });

    $.when.apply(null, ds).then(function() {
      // recursion may be here or...?
    });
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Damir Makhmutov, 2017-04-25
@gzhegow

You don't need recursion, just a loop is enough.
Example:

const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunks = 3;

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

let promise = Promise.resolve();

for (let i = 0; i < data.length; i += chunks) {
  const slice = data.slice(i, i + chunks);

  promise = promise.then(() => Promise.all(
    slice.map(() => console.log(i))
  ));
}

promise.then(() => console.log('all done'));

V
Vlad Feninets, 2017-04-25
@fnnzzz

it's easier to use Promise, it has the Promise.all method, which will transfer control to the next then only when all N-calls to the API have completed

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question