zoukankan      html  css  js  c++  java
  • 比callback更简洁的链式执行promise

    promise自己理解的也不够深刻,具体知识点不在这里细说了

    直接上个例子,清晰明了,自己去悟吧

    <script type="text/javascript">
        //模拟Promise,改善resolve原型方法
        var Promise = function () {
            this.thens = [];
        };
        Promise.prototype = {
            constructor: Promise,
            then: function(callback){
                this.thens.push(callback);
                return this;
            },
            resolve: function () {
                var t,p;
                t = this.thens.shift();
                t && (p = t.apply(null, arguments));
                while(t && !(p instanceof Promise)){
                    t = this.thens.shift();
                    t && (p = t.call(null, p));
                }
                if(this.thens.length){
                    p.thens = this.thens;
                };
            }
        }
        function f1() {
            var promise = new Promise();
            setTimeout(function () {
    
                console.log(1);
                promise.resolve();
            }, 5000)
    
            return promise;
        }
    
        function f2() {
            var promise = new Promise();
            setTimeout(function () {
                console.log(2);
                promise.resolve();
            }, 5000);
            return promise;
        }
    
        function f3() {
            var promise = new Promise();
            setTimeout(function () {
    
                console.log(3);
                promise.resolve();
            }, 5000)
    
            return promise;
        }
    
        function f4() {
            console.log(4);
            return 11;
        }
    
        function f5(x) {
            console.log(x+1);
        }
    
        function f6() {
            var promise = new Promise();
            setTimeout(function () {
    
                console.log(6);
                promise.resolve();
            }, 5000)
    
            return promise;
        }
    
        function f7() {
            console.log(7);
        }
    
        var that = f1().then(f2).then(f3).then(f4).then(f5).then(f6).then(f7);
    
    
    </script>
  • 相关阅读:
    poj3278 Catch That Cow
    poj2251 Dungeon Master
    poj1321 棋盘问题
    poj3083 Children of the Candy Cor
    jvm基础知识—垃圾回收机制
    jvm基础知识1
    java面试基础必备
    java soket通信总结 bio nio aio的区别和总结
    java scoket aIO 通信
    java scoket Blocking 阻塞IO socket通信四
  • 原文地址:https://www.cnblogs.com/djdliu/p/5614464.html
Copyright © 2011-2022 走看看