等待x时间,如果没有响应,则返回

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

我正在尝试使用http npm模块测试HTTP请求。如果请求不成功,则不会提供响应。我正在尝试这样做,因此,如果3秒钟内没有响应,它将运行诸如console.log('didnt work')之类的代码。

我有:

http.get({
    path: 'http://google.com'
}, function (response) {
    if (!response) {
        console.log('didnt work')
    } else {
        console.log('worked')
    }

});
node.js http
1个回答
0
投票

[首先,请注意,http请求是异步操作,结果是响应还是超时都是事件驱动的。因此,在响应或超时发生之前,这里没有任何阻塞。相反,您注册事件的回调或侦听器,然后对它们进行响应。

更具体地说,您可以将timeout功能用于http.get()。文件here

request.setTimeout(timeout[, callback])

timeout <number> Milliseconds before a request times out.

callback <Function> Optional function to be called when a timeout occurs.
                    Same as binding to the 'timeout' event.

Returns: <http.ClientRequest>

Once a socket is assigned to this request and is connected 
`socket.setTimeout()` will be called.

如果在设置的超时时间内未收到任何响应,则它将生成超时事件,调用回调并关闭套接字。您可以将其用作套接字的事件驱动结论,就像等待data事件一样。

© www.soinside.com 2019 - 2024. All rights reserved.