Fork me on GitHub

自用迷你版的Deferred

啥也不说贴代码,项目用

/**
     * 迷你版的deferred
     */
    function Deferred(func) {
        if (this instanceof Deferred === false) {
            return new Deferred(func)
        }
        var tuple = [];
        var promise = {
            resolve: function() {
                var t = tuple.shift(),
                    n;
                t && (n = t.apply(null, arguments), n instanceof Deferred && (n.tuple = tuple));
            },
            then: function(n) {
                return tuple.push(n), this;
            }
        }
        if (func) {
            func.call(promise, promise.resolve);
        }
        return promise;
    };

 

demo1

var d = new Deferred();

    setTimeout(function() {
        d.resolve('aaaa')
    }, 500)

    d.then(function(bbb){
        console.log(bbb)
    })

 

demo2

Deferred(function(resolve) {
    resolve('aaaa')
}).then(function(bbb) {
    console.log(bbb)
})

  

posted on 2014-05-22 14:43  【艾伦】  阅读(598)  评论(3编辑  收藏  举报