碼農干貨系列【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! =  =!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM