셀프 미니어처 Deferred
2768 단어 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)
})