【问题标题】:setTimeout() callback not called after a while一段时间后未调用 setTimeout() 回调
【发布时间】:2022-07-01 14:50:36
【问题描述】:

我有一个看起来像的函数

async function longPoll() {
    let timeout = 0
    try {
        // perform longPoll tasks
        let response = await axios.get(config.url)
        const data = response.data && response.data.data
        if (!Array.isArray(data)) {
            return
        }
        await Promise.all(data.map(async(item) => {
            try {
                // send message via WhatsApp using 'whatsapp-web.js'
                let chatId = getChatId(item)
                let text = getText(item)
                await client.sendMessage(chatId, text)
            } catch (e) {
                // some logging
                return
            }
            try {
                // report sending is ok
                let response = await axios.get(config.confirmationUrl)
            } catch (e) {
                // some logging
            }
        }))
    } catch (e) {
        if (e.response) {
            let status = e.response.status
            let statusText = e.response.statusText
            console.error(`Server response ${status} ${statusText}`)
        } else if (e.request) {
            console.error('No response from server.')
        } else {
            console.error('Failed to create request.')
        }
        timeout = 5000
    } finally {
        setTimeout(longPoll, timeout)
    }
}

longPoll() // kick off

一开始,它运行良好。一段时间后,longPoll() 不再被调用。为什么会这样?

我正在使用 NodeJS v16.14.0

【问题讨论】:

  • 嗯,为什么要投反对票?
  • 我没有投反对票,但可能是因为您没有发布包含问题的代码。发布的代码看起来是正确的,并且在许多应用程序中都可以正常工作。为什么函数是async?没有足够的细节来回答这个问题。添加一些调试细节。
  • @jabaa 一切都在trycatch 之内.. 所以我不知道是否有任何问题..
  • 我们也不知道。这可能是投反对票的原因。 // some checking & logging 部分可能很有趣。
  • 请提供minimal reproducible example。将axios.get(config.url) 替换为实际数据,例如jsfiddle.net/wg9zr1jv

标签: javascript node.js


【解决方案1】:

问题是由网络问题引起的。它通过向 axios.get() 添加超时来解决

【讨论】:

    【解决方案2】:

    调用longpoll 函数的超时时间在longpoll 内部。
    如果要对函数调用超时,则超时必须在该函数之外。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多