我已经使用JavaScript API实现了incremental synchronization of Google Calendar Events list的递归功能,除了resolve()
之外,一切似乎都有效,我不明白为什么......
我错过了什么?
syncEvents (calendarId) {
let eventsItems = []
let syncToken = null
let pageToken = null
function next(params) {
return new Promise((resolve) => {
gapi.client.calendar.events.list( params ).then( (response) => {
syncToken = response.result.nextSyncToken;
pageToken = response.result.nextPageToken;
let items = response.result.items
eventsItems.push(items)
if (pageToken) {
return next({
'calendarId': params.calendarId,
'pageToken': pageToken,
'syncToken': syncToken
})
}
if (syncToken) {
console.log('ok now resolve!') // <= This is called...
resolve(response)
}
})
})
}
next({'calendarId': calendarId}).then( (result) => {
console.log(eventsItems) // <= And this is not called...
})
}
谢谢!
答案 0 :(得分:1)
如果我可以尝试使用一些新的异步/等待糖,那么你不需要任何递归函数:)
async syncEvents(calendarId) {
const eventsItems = []
const query = {calendarId}
while (true) {
const response = await gapi.client.calendar.events.list(query)
const {nextSyncToken, nextPageToken, items} = response.result
eventsItems.push(items)
if (nextPageToken) {
query.pageToken = nextPageToken,
query.syncToken = nextSyncToken
} else {
return eventsItems
}
}
}
答案 1 :(得分:0)
它只能解决递归堆栈末尾最深的承诺。 Resolve永远不会被调用堆栈中更高的任何promise,因为返回在解析之前被调用。