啥也不说贴代码,项目用
/** * 迷你版的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) })