因此,我已经做了很多这方面的疑难解答,我的头撞墙。大多数情况下,我对承诺及其工作方式非常熟悉,并已将其用于少数项目。我遇到了让我所有的承诺,在使从谷歌日历API和脚本来计算结果数组的长度回调函数来使用不同的日历数据多次打电话给做完了一点小麻烦。下面是相关代码:jQuery当不按预期延期承诺
(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.after中解析出最终的promise后推送到数组,然后用它来执行.apply到数组 –
'$ .when()'实际上是脑死亡,使用时更是如此用jQuery Ajax调用。它不解析为数组。它解析为N个单独的参数,每个参数都可能是一个数组。为了处理任意数量的结果,你必须在'.when(...)。then(fn)''中处理传递给'fn'的'arguments'对象。研究jQuery文档中的'.when()'示例,特别是在使用Ajax调用时。 – jfriend00