gpt4 book ai didi

javascript - 如何将回调样本转换为延迟对象?

转载 作者:数据小太阳 更新时间:2023-10-29 05:23:12 28 4
gpt4 key购买 nike

我有一个接受回调函数的函数,我在其中将数据传回。可以将其转换为延迟对象以便更好地练习吗?

这是我得到的:

    var chapters;
var getChapters = function (fnLoad) {
//CACHE DATA IF APPLICABLE
if (!chapters) {
//CALL JSON DATA VIA AJAX
$.getJSON('/chapters.txt')
.done(function (json) {
//STORE DATA IN LOCAL STORAGE
chapters = Lawnchair(function () {
this.save(json, function (data) {
//CALL CALLBACK ON DATA
fnLoad(data);
});
});
});
} else {
//RETURN ALREADY CREATED LOCAL STORAGE
chapters.all(function (data) {
//CALL CALLBACK ON DATA
fnLoad(data);
});
}
};

然后我就这样简单地使用它:

this.getChapters(function (data) {
console.log(data);
});

如何在保持缓存方法的同时像 promise 一样使用它?

this.getChapters().done(function (data) {
console.log(data);
});

最佳答案

var chapters;
var getChapters = function (fnLoad) {
var d = new $.Deferred();
//CACHE DATA IF APPLICABLE
if (!chapters) {
//CALL JSON DATA VIA AJAX
$.getJSON('/chapters.txt')
.done(function (json) {
//STORE DATA IN LOCAL STORAGE
chapters = Lawnchair(function () {
this.save(json, function (data) {
//CALL CALLBACK ON DATA
d.resolve(data);
});
});
})
.fail(function() { d.reject(); });
} else {
//RETURN ALREADY CREATED LOCAL STORAGE
chapters.all(function (data) {
//CALL CALLBACK ON DATA
d.resolve(data);
});
}
return d.promise();
};

Relevant example

关于javascript - 如何将回调样本转换为延迟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17639408/

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