user2622344
user2622344

Reputation: 1086

Promises in loop

I have the following problem in Angular JS. I have this loop:

angular.forEach(objects, function(object)
{
    UpdateFactory.updateObjectInDatabase(version, object).then(function(newVersion)
    {
    version = newVersion;
        alert("Update successful! Version number increased.);
    });
});

But my problem is: I want only to call the Factory method, if previous call is finished. Otherwise I get status code 409, because of the wrong version.

I would be pleased if someone could help me!

Best regards.

Upvotes: 0

Views: 100

Answers (2)

Jesús Quintana
Jesús Quintana

Reputation: 1813

Try this

    var keys = Object.keys(objects)
    var i = 0;
    update(function() {
        console.log("should be called when the operation end");
    })

   function update(cb) {
        cb = (angular.isFunction(cb) ? cb : angular.noop);
        if(i <= keys.length-1 ) {
            i++; //increment the counter
            UpdateFactory.updateObjectInDatabase(version, objects[keys[i]])
            .then(function(newVersion) {
                version = newVersion;
                    alert("Update successful! Version number increased.");
                update(cb)
            }, function(){
                console.log("a promise return a reject"); 
                cb();
            });

        } else {
            cb() //Finish the operation
        }
    }

Only get the keys of the object and call the function when the promise ends, make a recursive call and stop when the keys ends

Upvotes: 0

Dieterg
Dieterg

Reputation: 16368

You can solve this with a recursive function that calls itself when previous request is done:

function update(objects, current) {
  UpdateFactory.updateObjectInDatabase(version, objects[current]).then(function (newVersion) {
     version = newVersion;

     if (objects[++current]) {
        update(objects, current);
     }
  });
}

// Start with first object
update(objects, 0);

Note: this assumes objects is an array of objects

Upvotes: 1

Related Questions