【问题标题】:Wait x amount of time, then return if no response等待 x 时间,如果没有响应则返回
【发布时间】:2020-03-24 12:31:03
【问题描述】:

我正在尝试使用 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】:

首先,请记住,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 事件一样。

【讨论】:

    猜你喜欢
    • 2013-08-06
    • 1970-01-01
    • 2014-07-04
    • 2022-06-16
    • 2019-02-16
    • 2020-12-30
    • 2014-10-23
    • 2016-06-26
    • 2013-11-11
    相关资源
    最近更新 更多