【问题标题】:Do NodeJS functions timeout if it takes too long ?如果需要太长时间,NodeJS 函数会超时吗?
【发布时间】:2018-03-07 07:52:32
【问题描述】:

我有一些第三方 API,它们运行的​​函数需要大约 30 分钟才能返回结果(它们会进行一些冗长的计算)。 现在,如果我使用 Nodejs 通过适当的回调调用这样的 API,Nodejs 默认会等待 30 分钟让函数返回结果还是超时? 如果超时,有没有办法增加等待时间?

【问题讨论】:

  • “第三方API”如何集成到节点环境中? HTTP 请求肯定会超时。
  • API 的文档应该说明什么是“适当的回调”。是的,如果应该这样使用它会等待。

标签: javascript node.js callback async-await


【解决方案1】:

我假设您使用的是express,如果您使用的是快递,您可以添加以下代码以增加等待时间。

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;

否则你可以使用纯http

var http = require('http');
var server = http.createServer(function (req, res) {
  setTimeout(function() {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
  }, 200);
}).listen(1337, '127.0.0.1');

server.timeout = 20;

【讨论】:

  • 我看不出 express 与“一些第三方 API”有什么关系?
  • 根据问题Nodejs是用来调用第三方API的,所以我们必须在nodejs端处理等待时间来消除超时的事情。
  • “调用第三方 API”可以表示任何含义。不,我们不能假设 OP 将request 用于任何事情
  • @SuvethanNantha - 谢谢。这很有用。
【解决方案2】:

Linux 的默认值可以使用 20s - 120s 之间的任何时间作为超时 http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout

根据您使用的请求库,您在设置超时时可能有不同的语法。我个人非常喜欢request,参考这里https://github.com/request/request

request.get('http://10.255.255.1', {timeout: 1500}, function(err) {
    console.log(err.code === 'ETIMEDOUT');
    // Set to `true` if the timeout was a connection timeout, `false` or
    // `undefined` otherwise.
    console.log(err.connect === true);
    process.exit(0);
});

我不认为 N​​odeJS 函数本身会超时。

【讨论】:

    猜你喜欢
    • 2018-07-04
    • 1970-01-01
    • 2012-01-10
    • 2020-11-12
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    相关资源
    最近更新 更多