1

I'm working on a feature for my work and I've come to a crossroads. I'm completely new to Ajax, and am trying to implement a queue to manually handle the Ajax requests as opposed to the browser. I've done some research and looked at this answer, however the requests I'm going to be sending won't be declared beforehand, as the whole website is dynamic. Is there a way of using the code there in tandem with the JQuery.when() function described here? I was thinking along the lines of:

$.when(d1).done(function(var d2=$.Deferred()) {
    d2.resolve();
}
d1.resolve();

However this implementation is not working for me. Thanks for any help I can get!

Community
  • 1
  • 1
Sam Worrod
  • 33
  • 6

1 Answers1

1

You can try wrapping the requests in ES6 promises, then adding them to an array, and calling Promise.all() with the array as an argument. Via the documentation:

The Promise.all() method returns a single Promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first promise that rejects.

It wouldn't care where the requests were coming from, just that they either resolve or reject.

It'd look a little something like this:

        let promiseArray = [];
        for (let i = 0; i < 3; i++) {
            let promise = new Promise((resolve, reject) => {
                $.ajax({
                    url: url,
                    type: 'GET',
                    success: data => resolve(data),
                    error: err => reject(err)
                });
            });
            promiseArray.push(promise);
        }
        Promise.all(promiseArray).then((data) => {
            //Will return an array of the successful requests, or will reject on the first rejected request
            console.log(data);
        });

The support for ES6 promises isn't quite universal yet, so I'd use a transpiler just in case, but it seems like Promise.all could help you.

Ryan Giordano
  • 46
  • 1
  • 4