Angularjs then function from promise in for loop. How to access index of current item?

Issue

I have a loop that loops over all properties of object in AngularJS and for every property it make AJAX call using Restangular.
When request is finished I would like to set isNew property of that item to false.

At the moment current implementation that is working looks something like this (parts that are not important are removed):

var promises = [];
for (var prop in items) {
    if (items.hasOwnProperty(prop)) {

        var newPromise = REST.Items
                        .all('items')
                        .post({ key: items[prop].key, value: items[prop].value })
                        .then(function (prop) {
                            items[prop].isNew = false;
                        }.bind(this, prop));

        promises.push(newPromise);
    }
}
return $q.all(promises);

And this implementation seems to work just fine but the jshint is complaining for functions being created inside a loop: ” Don’t make functions within a loop. }.bind(this, prop));”

What is best way to refactor this part of code?

Solution

See the solution in the snippet below

var promises = [];
var handler = function (prop) {
    items[prop].isNew = false;
};

for (var prop in items) {
    if (items.hasOwnProperty(prop)) {

        var newPromise = REST.Items
                        .all('items')
                        .post({ key: items[prop].key, value: items[prop].value })
                        .then(handler.bind(this, prop));

        promises.push(newPromise);
    }
}

return $q.all(promises);

Answered By – Alexander Elgin

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.