0

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.

1
  • Not sure if this would help, but try wrapping the forEach loop's inside in an immediate function: angular.forEach(objects, function(object) { (function(obj) { /* UpdateFactory on obj */ })(object) }); Commented Feb 18, 2015 at 8:51

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

That is a really good advice! Thank you very much. I'll try this immediately.
@user2622344 Mark this answer as correct so that it would help other who are getting same problem..
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.