gpt4 book ai didi

javascript - 解决未在递归 Promise 函数中调用的问题

转载 作者:行者123 更新时间:2023-12-03 02:05:25 24 4
gpt4 key购买 nike

我做了一个递归函数来实现 incremental synchronization of Google Calendar Events list使用他们的 JavaScript API,除了 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...
})

}

谢谢!

最佳答案

如果我可以尝试使用一些新的异步/等待糖,那么你不需要任何递归函数:)

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
}
}
}

关于javascript - 解决未在递归 Promise 函数中调用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49833922/

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