【发布时间】:2017-06-25 06:22:10
【问题描述】:
因此,我已经对此进行了很多故障排除,并且正在将头撞到墙上。在大多数情况下,我对 Promise 及其工作方式非常熟悉,并且在一些项目中使用过它们。我在完成对来自 Google Calendar API 的不同日历数据的多次调用以及脚本计算结果数组的长度以在回调函数中使用时完成所有承诺时遇到了一些麻烦。以下是相关代码:
(function($){
var baseUrl = 'https://www.googleapis.com/calendar/v3/calendars/',
apiKey = 'xxxxxxxxxxxx',
calendarData = [],
events = [],
allCalendars = [],
eventsToDisplay = 9;
/* Get all the calendars that we have registered */
function getCalendars() {
return $.getJSON(ajaxurl, {action: 'wps_get_calendars'});
}
/* Get the events for a calendar by the calendar ID */
function getCalendarEvents(calendarID) {
return $.getJSON(baseUrl + calendarID + '/events', {
maxResults: '4',
orderBy: 'startTime',
timeMin: moment().format(),
singleEvents: true,
key: apiKey
}).success(function(data){
calendarData.push(data.items);
});
/* Create a collection of promises */
var promises = getCalendars().then(function(calendars){
var deferreds = [];
calendars.forEach(function(calendar){
deferreds.push(
getCalendarEvents(calendar.googleCalendarId)
);
});
return deferreds;
});
/* Wait until all the promises have completed, then sort the events */
$.when.apply($, promises).then(concatEvents);
})(jQuery);
基本上问题是在最后一次致电$.when 时,我正在等待我必须完成的一系列承诺。 $.when 似乎不起作用,因为如果我尝试在 $.when 回调中将 calendarData 数组记录到控制台,它会返回一个没有计算长度的数组。我能够弄清楚如何做到这一点的唯一方法是在回调中使用setTimeout,并将其设置为大约 2000 毫秒,但这并不理想,因为取决于网络连接、API 可用性等。 ,接收所有数据的时间可能完全不同。
就像我在控制台中看到的一样,当我尝试在$.when 回调中记录结果时,我得到了这个“长度更少”的数组,因为脚本无法迭代似乎认为它是空的:
知道我在这里做错了什么吗?提前感谢您的帮助。
【问题讨论】:
-
1) deferred.then 返回一个新的承诺,而不是你返回的数组。 2) 在 getcalendars 解决之前,您将无法访问该数组。 3) 使您的承诺数组超出 .then 的范围,并使用 getcalendars.then 填充它。使用另一个外部延迟,您将从 getcalendars 解决。在最终承诺被推送到数组之后,然后使用它来执行 .apply 到数组
-
$.when()真的是脑残,在与 jQuery Ajax 调用一起使用时更是如此。它不解析为数组。它解析为 N 个单独的参数,每个参数都可能是一个数组。要处理任意数量的结果,您必须处理在$.when(...).then(fn)中传递给fn的arguments对象。研究 jQuery 文档中的$.when()示例,尤其是与 Ajax 调用一起使用时。
标签: javascript jquery arrays promise deferred