tqrecords
tqrecords

Reputation: 542

Loop through ajax function using promises

I just started looking into es6-promises and I'm having trouble wrapping my head around it. In my application, I'm trying to return data through an ajax call and continuing looping until no more data is found (essentially paging).

Here is the ajax call which returns a promise object:

function getDeals(start, url) {
   return Promise.resolve($.ajax({
        type: 'GET',
        url: url,
        data: { start: start },
        global: false,
        success: function() {},
        error: function() {}
    }));
}

Here is the containing function:

var start = 0;

getDeals(start, url).then(function (data) {
    // The call returns a more data flag if there are more records
    moreData = data.moreData;
    start = data.records.count;
}).then(function () {
    if (moreData) {
        // Here is where I want to continue calling the function 
        // until no more records are found
        getDeals(start, url);
    }
});

Each call returns 100 records, so I need to continue looping through until the moreData flag is false. Also, not sure if the promise method is the most efficient way to go about doing this.

Upvotes: 0

Views: 209

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21628

$.ajax already returns a promise for you so you don't need to create another one, just pass in the success and fail functions you want to run.

function getDeals(start, url, success, error) {
    $.ajax({
        type: 'GET',
        url: url,
        data: { start: start },
        global: false,
        success: success,
        error: error
    });
}

and call it

var start = 0;

getDeals(start, url, success);

function success (data) {
    // The call returns a more data flag if there are more records
    moreData = data.moreData;
    start = data.records.count;
    if (moreData) {
    // Here is where I want to continue calling the function 
            // until no more records are found
        getDeals(start, url, success);
    }
}

Upvotes: 2

Related Questions