Last active
April 13, 2016 14:56
-
-
Save icfantv/48f7850f5da52f7594d4 to your computer and use it in GitHub Desktop.
How to NOT do a nested promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(...); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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']; |
Author
icfantv
commented
Mar 14, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment