Randheer Singh Chouhan Randheer Singh Chouhan - 3 months ago 6
AngularJS Question

How to perform a recursive loop?

I have the following code which gets the data from a third party API, which is at example.com:

$scope.buttonClick = function () {
$http.get('https://example.com').
success(function (data, status, headers, config) {
console.log(data.pagination.next);

for (var key in data.applicants) {
if (data.applicants[key].email == "xxx@example.org") {
console.log('found');
console.log(data.XXX[key].id);
}
}
}).
error(function (data, status, headers, config) {
// log error
});
}


Now it contains pagination which is in
data.pagination.next


If data which is coming from third party can be more then 1 page, I want to perform this operation recursively to check if email id matches, then it return the id which is in if condition, Above code work well if there is one page.

Answer

You should separate the code for checking from the code that's retrieving, and wrap the latter in a function. Then with a few if/elses just do pretty much the same.

$scope.buttonClick = retrieveData;

function retrieveData( pageId ) {
    var params = { pageId: pageId || 1 };
    $http.get('https://zzz.com', params).
        success(function (data, status, headers, config) {
            var applicantFound = searchApplicantMail( data );
            if( ! applicantFound && data.pagination.next ) {
                return retrieveData( data.paginantion.nextPage );
            }
            doSomethingWith( applicantFound );
        }).
        error(function (data, status, headers, config) {
            // log error
        });
}

function searchApplicantMail( data ) {
    for (var key in data.applicants) {
        if ( ! data.applicants.hasOwnProperty(key) ) {
            continue;
        }
        if (data.applicants[key].email == "xxx@xxx.com") {
            return data.applicants[key];

        }
    }
    return false;
}
Comments