简体   繁体   中英

Angular promise multiple times

I'm trying to replicate a couchDB like system. My backend is Parse server and my frontend is Ionic (1)

What i'm trying to achieve is to fasten my application with localstorage.

Currently: GetUserAds

-> Has localstorage?

--> Yes

---> Return localstorage

--> No

---> Get database call

----> Return and put local

But what i really would like is the local return to fetch the database in background and return that data as well if it's changed

This is because my application has many users and changes a lot.

Could i do something like this.

getUserAds(user).then(function(data) {
//Local data
}).then(function(dataDB) {
//Database updated data
})

You could use the notify callback provided on angular promises:

function UserService($timeout, $q) {
    var users = ["user1", "user2"]; //localStorage.getItem('users');
    function get() {
    var deferred = $q.defer();
    //call your backend here $http.get('....')
    $timeout(function() {
      //if(remoteUsers !== users) {
                deferred.resolve({local: false, users: users.concat('user3')});
      //}

    }, 3000);
    $timeout(function() {
    if(users) {
        deferred.notify({local: true, users: users});
    }

    }, 100)

    return deferred.promise;
  }

    return {
    get: get
  };
}

and in your controller

function MyCtrl($scope, $users) {
    $scope.name = 'Superhero';
    $scope.myUsers = [];

    $users.get()
        .then(setUsers, null, setUsers);

     function setUsers(users) {
        $scope.myUsers = users;
      }
}

Here you can see a little jsfiddle: http://jsfiddle.net/Lvc0u55v/1596/

You can do that if you use this service from the Angular API: Angular Promises .

This is how I would do it:

getUserAds(user).then(function(response) {
    // useMyData
});

function getUserAds {
    if( thereIsLocalData ) {
        return getLocalData(); // this returns a $q promise
    } else {
        return getDataDB() // Here I'm returning an $http Promise
    }
}

function getDataDB (params)  {
    return $http.get(host, params, {}); // I'm returning the $http Promise!
}

function getLocalData (params) {
    return $q(function(resolve, reject) {
        resolve(myLocalData);
  }); // return the $q promise!
}

This way you are using local communications the same way as Online communications and you can simplify your logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM