javascript - AngularJS : promises, can you pass a promise back after using .then()? -
i'm still new angular , promises hope have correct idea here.
i have data layer service uses restangular data, returns promise, this...
datastore.getusers = function (params) { return users.getlist(params); };
then, controller has called function receives promise back, this...
$datastore.getusers(params).then(function (response) { $scope.users = response; }, function(response) { $log.error("get users returned error: ", response); });
this working well, i'd use promise inside of datastore before passing back. i'd use .then() method check if failed , logging, then, sucess function , failure function i'd return original promise controller.
my controller able use .then() method is, in fact, don't want controller code change @ all, datastore code.
here's semi-pseudo code show i'd datastore function do...
datastore.getusers = function (params) { users.getlist(params).then(function (response) { $log("server responded") return original promise; }, function(response) { $log.error("server did not respond"); return original promise; }); };
you not far off @ in pseudo code. promises chain:
datastore.getusers = function (params) { return users.getlist(params).then(function (response) { $log("server responded") return response; }, function(failure) { $log.error("server did not respond"); // change throw if want angular lever logs return $q.reject(failure); }); };
the controller gets resolved/rejected same value. log requires tapping promise must add .then
handler deal it. other promise libraries have convinicene methods $q minimalistic in regard.
alternatively, can use nicer catch syntax, propagate errors logs:
datastore.getusers = function (params) { return users.getlist(params).then(function (response) { $log("server responded") return response; }).catch(function(failure) { $log.error("server did not respond"); throw failure; }); };
Comments
Post a Comment