我正在尝试制作一个长期轮询客户端,该客户端会无限期地轮询API。由于使用python的同步特性,因此在使用python时非常简单,但是在javascript中,循环在发送新请求之前不会等待post请求完成。进一步的研究表明,我不应该使用循环,而应该使用递归函数。
这是简化的javascript代码,但恐怕最终会产生错误“超出最大调用堆栈大小”。
function collect(date) {
needle('post', url, pollData, { json: true, response_timeout: 60000 })
.then(response => {
try {
console.log(response.body.toSTring())
collect()
}
catch (error) {
console.log(`Response Code: ${response.statusCode}, ${error.message}`)
collect()
}
})
.catch(error => {
console.log(error.message)
collect()
})
}
collect()
有人可以指导我实现无限长轮询而不产生错误的正确方法吗?谢谢