gpt4 book ai didi

javascript - node.js 回调和递归

转载 作者:搜寻专家 更新时间:2023-10-31 23:51:46 25 4
gpt4 key购买 nike

我正在使用 google api 获取邮箱中所有邮件的列表。 API 对列表进行分页,每次调用都会返回下一页,因此我必须递归调用它:

const fetch = (cb, next) => {
google.gmail('v1').users.messages.list({
auth: oauth2Client,
userId: 'me',
pageToken: next
}, cb)
}
const store = (err, result) => {
// do something with result and then
if (result.nextPageToken) {
fetch(store, result.nextPagetToken)
}
}

fetch(store)

有没有更好的方法来避免递归,这样我就不会破坏堆栈?

最佳答案

代替:

fetch(store, result.nextPagetToken)

你可以使用:

process.nextTick(fetch, store, result.nextPagetToken);

但如果类似的事情已经在 messages.list() 回调中完成,那么它甚至可能没有必要。除了适当的尾调用优化已经在 J​​S 中得到支持,并且当您使用 --harmony 标志时在 Node 中从 6.5.0 版本开始可用,请参阅:

还有我的tco即使在最旧版本的 Node 中也可以无限递归的模块。

关于javascript - node.js 回调和递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42806674/

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