gpt4 book ai didi

javascript - 如何从延迟对象 JQuery 中获取返回值

转载 作者:行者123 更新时间:2023-11-30 12:43:45 25 4
gpt4 key购买 nike

我正在编写一个函数来加载事件(用于日历),它应该返回要由 Mustache 解析的数据。我遇到的问题是我找不到在 request.done() 中返回已处理数据的方法

这是我的功能

this.load = function() {
var events = createArray(7, { content: [] });
var data = {
from: Math.floor(this.week[0].valueOf() / 1000),
to: Math.floor(this.week[6].valueOf() / 1000)
};
var request = $.ajax({
url: this.loadPath,
data: data,
type: 'POST'
});

request.done(function(response) {
response = JSON.parse(response);
response.forEach(function(event) {
event.date = new Date(event.date);
var thisEvent = {
id: event.id,
time: event.date.format('HH:MM'),
title: event.title,
description: event.description,
color: event.color,
link: event.link
};

// Why is thisEvent added to each events[].content and not just for events[day].content?
events[event.date.getRealDay()].content.push(thisEvent);
});
});

// return statement has to be executed only when request.done() has finished
// or find a way to return directly from request.done()
return { events: events };
};

谢谢你的帮助

编辑:找到解决方案

this.load = function() {
var data = {
from: Math.floor(this.week[0].valueOf() / 1000),
to: Math.floor(this.week[6].valueOf() / 1000)
};
var request = $.ajax({
url: this.loadPath,
data: data,
type: 'POST',
context: this
});
var deferred = $.Deferred();

request.done(function(response) {
var events = createArray(7, { content: [] });
response = JSON.parse(response);

response.forEach(function(event) {
event.date = new Date(event.date);
var thisEvent = { // Why does the
id: event.id,
time: event.date.format('HH:MM'),
title: event.title,
description: event.description,
color: event.color,
link: event.link
};
events[event.date.getRealDay()].content.push(thisEvent); // Why is thisEvent added to each events[].content and not just for events[day].content?
});
deferred.resolveWith(this, events);
});
request.fail(deferred.reject);

return deferred.promise();
};

从我可以调用的另一个函数:

this.load().done(function(events) {
this.events = events;
this.render();
});

最佳答案

一种解决方案是在完成后使用回调:

this.load = function(cb) {
//...
request.done(function(response) {
// do your stuff with the events etc.
cb(events);
}
};

然后像这样调用它

load(function(events){
// events manipulated and ready to use
});

或者创建一个新的 promise 并解决它:

this.load = function() {
var dfd = $.Deferred();
//...
request.done(function(response) {
// do your stuff with the events etc.
dfd.resolve(events);

}).fail(dfd.reject); // reject on error

return dfd.promise();
};

以类似的方式调用它:

load.done(function(events){
// handle events
}).fail(function(){
// handle errors
});

关于javascript - 如何从延迟对象 JQuery 中获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23406574/

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