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>
  • 相关阅读:
    Oracle Instance
    第03章-VTK系统概述(1)
    二叉查找树BST----java实现
    [Golang] 从零開始写Socket Server(2): 自己定义通讯协议
    linux之SQL语句简明教程---LIKE
    spring mvc 入门示例
    MyBatis与Spring集成
    MyBatis 一对一关联查询
    MyBatis CRUD Java POJO操作
    eclipse xml自动提示
  • 原文地址:https://www.cnblogs.com/djdliu/p/5614464.html
Copyright © 2011-2022 走看看