gpt4 book ai didi

javascript - 延期/ promise 混淆和实现

转载 作者:行者123 更新时间:2023-11-30 17:22:01 26 4
gpt4 key购买 nike

<分区>

如果我想自己实现deferred,这样做是否正确(试图理解内部逻辑):

延迟算作一种行为模式吗?

deferred 和 promise 有什么区别?

function Deferred() {
var d = {},
f = {},
a = {},
state = 'pending';

return {
resolve: function(){
state = 'resolved';
a.fn.apply(a.context, arguments);
d.fn.apply(d.context, arguments);
},

reject: function(){
state = 'rejected';
a.fn.apply(a.context, arguments);
f.fn.apply(f.context, arguments);
},

done: function(fn, context) {
d = {fn: fn, context: context};
return this;
},

fail: function(fn, context) {
f = {fn:fn, context: context};
return this;
},

always: function(fn, context) {
a = {fn:fn, context: context};
return this;
},

state: state
}
}

应用示例:

var obj = Deferred();
obj.done(function(arg){
console.log('we are done here. why? -', arg);
}, window)
.always(function(arg){
console.log('print that in any case. and some details:', arg);
}, window)
.fail(function(arg){
console.log('we failed here. why? -', arg);
}), window;


obj.reject('some arguments');
obj.resolve({argument: 'hooray!'});

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com