0

In the success callback to an ajax query, I have to

a) update the property of an object in an array (and I have to locate that object in the array)
b) save that array again in storage 
c) broadcast an event

I'm (trying to) accomplishing that by doing this (code below)

updateTheArray(myarray,'date', $scope.date);
myStorage.put(myarray);
$scope.$broadcast('alldone');

As I'm concerned these are happening out of order or could happen out of order,I would like to be able to do something like (in pseudo code) in the success callback

 var updated = updateTheArray();  //update a property on an object in array
 updated.promise().then(function(){
     myStorage.put(array);  //saves
  }).done(function(){
     $scope.$broadcast('alldone'); //broadcast
 }

However, the way I've written the storage and the updateTheArray function are not setup to do that.

Is there a way in Angular to make sure the next function only runs once the first one is complete?

Leaving aside the updateTheArray function, even if I try to use the storage function in promise like this

   var save = myStorage.put(array);
    save.promise().done(function(){
       console.log('blah');
    });

I get a cannot read property promise of undefined error, so how do I make that storage return a promise object?

updateTheArray (finds a particular object in an array and changes a property)

function updateTheArray(array, attr, value){
   var len = array.length;
   len = len -1;
   for (var i = len; i > 0; i --){
      if(array[i][attr] === value) { //find by date
         array[i]['completed'] = true; //set some property to true
      }
   }
}

storage

app.factory('myStorage', function(){
      return {

            get: function(){
                   return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
             },
            put: function(myarray){
                   localStorage.setItem(STORAGE_ID, JSON.stringify(myarray));
             }

       }
}
Leahcim
  • 40,649
  • 59
  • 195
  • 334

1 Answers1

0

As described in this answer, local storage calls are synchronous, so there is no need to wait for myStorage.put to complete.

The reason for the cannot read property promise of undefined error is that you aren't returning anything at all from your put function on myStorage (but, as above, you don't need to return a promise anyway as it's a synchronous call).

The updateTheArray implementation you have shown is also synchronous, so the whole thing should work in order as-is, without any callbacks or promises required.

Community
  • 1
  • 1
Mark Hughes
  • 7,264
  • 1
  • 33
  • 37