因此,我已經做了很多這方面的疑難解答,我的頭撞牆。大多數情況下,我對承諾及其工作方式非常熟悉,並已將其用於少數項目。我遇到了讓我所有的承諾,在使從谷歌日曆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