首页 > 代码库 > 迷你版Deferred

迷你版Deferred

直接贴代码:

/** * 迷你版的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)})

 

迷你版Deferred