Skip to content

Instantly share code, notes, and snippets.

@icfantv
Last active April 13, 2016 14:56
Show Gist options
  • Save icfantv/48f7850f5da52f7594d4 to your computer and use it in GitHub Desktop.
Save icfantv/48f7850f5da52f7594d4 to your computer and use it in GitHub Desktop.
How to NOT do a nested promise
someFunction() {
// do some stuff
MyService.doSomething().then(() => {
// do some stuff
AnotherService.doSomethingElse().then((blah) => {
// do something with blah
})
.catch(...)
.finally(...)
// do some more stuff
})
.catch(...)
.finally(...);
}
angular.module('app.services', [])
.service('MyService', MyService);
function MyService($q, $http) {
this.getSomething = function() {
return $http.get('foo'); // this natively returns a promise
}
var cache = [];
this.getSomethingElse = function(id) {
return $q(resolve, reject) {
if (/* id in cache */) {
var item = cache[0]; // or wherever it's at in the cache
resolve(item);
}
else {
/* fetch item from somewhere */
var item = "foo";
resolve(item);
}
// if an error happens and you can trap it
var error = "some error";
reject(error);
}
}
}
MyService.$inject = ['$q', '$http'];
@icfantv
Copy link
Author

icfantv commented Mar 14, 2016


someFunction() {

  // do some stuff

  MyService.doSomething().then(() => {

    // do some stuff

    return AnotherService.doSomethingElse()
  })
  .then((...) => {
    // process result from AnotherService.doSomethingElse()
  })
  .catch(...)
  .finally(...);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment