미니 버전 Deferred

2070 단어
코드에 직접 부착:
/**
 *     deferred
 */
function Deferred(func) {
    if (this instanceof Deferred === false) {
        return new Deferred(func)
    }
    var tuple = [];
    var promise = {
        resolve: function () {
            var t;
            while (t = tuple.shift()) {
                t.apply(null, arguments);
            }
        },
        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({
        name : 'breezefeng',
        age : 24,
        sex : ' '
    });
});

 d.then(function (globalInfo) {
    console.log(globalInfo.name);
}).then(function (globalInfo) {
    console.log(globalInfo.age);
}).then(function (globalInfo) {
    console.log(globalInfo.sex);
});

demo2:
Deferred(function (resolve) {
    setTimeout(function () {
        resolve('aaaa');
    });
}).then(function (bbb) {
    console.log(bbb)
})

좋은 웹페이지 즐겨찾기