如何使用JavaScript来longpoll多个URL?

问题描述 投票:0回答:1

目标是将多个longpoll连接打开到多个URL(例如example.com/user/1example.com/user/2等),并在更新数据时对其进行处理并重新连接。这是到目前为止我所拥有的一个简单示例:

async function longpoll(url) {
    http.get(url, (response) => {
        response.on('data', (data) => {
            // do something with data
        }
        response.on('end', () => {
            // cleanup
            longpoll(url)
        }
    }
}

我还有很多事情要做,但这是基本设置。这适用于单个网址,但是如果我尝试添加更多内容(例如在循环中),它将关闭除一个以外的所有内容。有人可以指出我能够实现这一目标的方向吗?

javascript node.js long-polling
1个回答
0
投票
function startLongPollingForMultipleUrls(urls) {
    urls.forEach(url => longpoll(url);
}

function longpoll(url) {
    http.get(url, (response) => {
        response.on('data', (data) => {
            // do something with data
        }
        response.on('end', () => {
            // cleanup
            // Use a timeout to wait 1 second between calls
            setTimeout(() => longpoll(url), 1000)
        }
    }
}

const myUrls = ['example.com/user/1', 'example.com/user/2']

startLongPollingForMultipleUrls(myUrls);
© www.soinside.com 2019 - 2024. All rights reserved.