博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Angular-Scaled Web] 9. Control your promises with $q
阅读量:6814 次
发布时间:2019-06-26

本文共 1645 字,大约阅读时间需要 5 分钟。

Learn how to manually control how asynchronous requests are 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 will take this a step further but 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) {        var CategoriesModel = {},            URLS = {                FETCH: 'data/categories.json'            },            categories;        function extract(result) {            return result.data;        }        function cacheCategories(result) {            categories = extract(result);            return categories;        }        CategoriesModel.getCategories = function() {            return (categories) ? $q.when(categories) : $http.get(URLS.FETCH).then(cacheCategories);        };        CategoriesModel.getCategoryByName = function(categoryName) {            function findCategory(){                return _.find(categories, function(c){                    return c.name == categoryName;                })            }            return $q(function(resolve, reject) {                //resolve it when categories are set                if(categories){                    resolve(findCategory());                }else{                    //if not set, get the categories                    CategoriesModel.getCategories()                        .then(function() {                            resolve(findCategory());                        })                }            })        };        return CategoriesModel;    });

 

转载地址:http://mibzl.baihongyu.com/

你可能感兴趣的文章
SpringBoot和数据库连接
查看>>
二叉搜索树
查看>>
网页小技巧-360doc个人图书馆复制文字
查看>>
delete删除-some
查看>>
maven阿里云中央仓库
查看>>
15.12.14listbox列表框
查看>>
sql 行转列
查看>>
(转)Python新手写出漂亮的爬虫代码1——从html获取信息
查看>>
配置Nim的默认编译参数 release build并运行
查看>>
图片下载
查看>>
《构建之法》第四章读后感
查看>>
python os.path.dirname()
查看>>
android 解析json数据格式
查看>>
Vs2013 头文件注释
查看>>
****** 六 ******、软设笔记【数据结构】-查找、静态查找表,哈希表
查看>>
[转] fitnesse中的Map处理
查看>>
js - 常用功能方法汇总(updating...)
查看>>
matlab 函数库
查看>>
Django博客功能实现—文章评论的显示
查看>>
Activity里面嵌入Fragment一点小代码
查看>>