zoukankan      html  css  js  c++  java
  • 码农干货系列【6】javascript异步编程之:世界上最短的Promise库

    类库源码

        var Promise = function () {
            this.thens = [];
        };
        Promise.prototype = {
            resolve: function () {
                var t = this.thens.shift(), n;
                t && (n = t.apply(null, arguments), n instanceof Promise && (n.thens = this.thens));
            },
            then: function (n) {
                return this.thens.push(n), this;
            }
        }

    使用方式

            function f1() {
                var promise = new Promise();
                setTimeout(function () {
                   
                    alert(1);
                    promise.resolve();
                }, 1500)
    
                return promise;
            }
    
            function f2() {
                var promise = new Promise();
                setTimeout(function () {
    
                    alert(2);
                    promise.resolve();
                }, 1500)
    
                return promise;
            }
    
            function f3() {
                var promise = new Promise();
                setTimeout(function () {
    
                    alert(3);
                    promise.resolve();
                }, 1500)
    
                return promise;
    
            }
    
            function f4() {
                    alert(4);
            }
          
            f1().then(f2).then(f3).then(f4)

    类库思路

    主要的思路就是将主Promise下的任务列表(thens)挂靠到子Promise下。当然该库可以封装至ajax、domready等耗时的场景当中,使其可以”thenable",如:

              $$.ajax("assets/xxx.php", {
                         method: "GET",
                         data: "q=1&rand=" + Math.random()
                     }).then(function (msg) {
                         alert(msg.responseText)
                     });
    have fun! =  =!
  • 相关阅读:
    点击CheckBox让Gridview控件在编辑与正常状态之间切换
    BMP图片转换为JPEG图片
    ASP.NET截取网页注释行之间的内容
    Mouse点击之后,复制GridView控件的数据行
    Mouse单击高亮GridView数据行
    ASP.NET div信息提示框显示几秒后隐藏
    RDLC报表带搜索与传参数功能演示(ASP.NET MVC)
    ASP.NET MVC应用程序使用axd格式文件
    Nginx通过geo模式实现限速白名单和全局负载均衡
    MySQL 下mysqladmin日常管理命令总结
  • 原文地址:https://www.cnblogs.com/iamzhanglei/p/2924680.html
Copyright © 2011-2022 走看看