Learn how to manually control how asynchronous requests is handled with the use of promises. Because $http is built to work with promises, we saw a foreshadow of them in the previous lesson. We'll take this a step further if seeing how to manually create a promise and then resolve or reject it as we see fit.
Angular.module (' Eggly.models.categories ', []). Service (' Categoriesmodel ',function($http, $q) {varCategoriesmodel ={}, URLS={FETCH:' Data/categories.json '}, categories; functionExtract (Result) {returnResult.data; } functioncachecategories (Result) {categories=extract (Result); returncategories; } categoriesmodel.getcategories=function() { return(categories)?$q. When (categories): $http. Get (URLS. FETCH). Then (cachecategories); }; Categoriesmodel.getcategorybyname=function(CategoryName) {functionfindcategory () {return_.find (Categories,function(c) {returnC.name = =CategoryName; }) } return$q (function(Resolve, reject) {//Resolve it when categories is set if(categories) {Resolve (Findcategory ()); }Else{ //if not set, get the categoriescategoriesmodel.getcategories (). Then (function() {Resolve (Findcategory ()); }) } }) }; returnCategoriesmodel; });
[Angular-scaled Web] 9. Control your promises with $q