javascript - 如果代码需要很长时间才能完成,如何在 node.js 中引发超时错误?

标签 javascript node.js

在 ruby 中我可以:

require 'timeout'

Timeout.timeout 10 do
# do smth > 10 seconds
end

它会引发超时错误以避免代码锁定,如何在 nodejs 中做同样的事情,nodejs #setTimeout 不符合我的需要

一种情况是,当我 http.get 超时(例如,netowrk 不稳定)时,我应该设置超时并处理失败的 get 请求,我希望 impl #timeout,我该怎么办?

try {
  timeout(10, function () {
    http.get("example.com/prpr")
  })
} catch (e) {
  if (e.message == "timeout") {
    // do smth
  } else {
    throw e
  }
}

最佳答案

您可以在此处查看基于 Promise 的方法。

使用 promise ,您可以传递一个要执行的函数,然后如果该函数引发异常,则调用标准的 catch

NPM 上有一个有用的基于 promise 的超时库(npm install promise-timeout request-promise),您可以在 Node 中使用它,类似于...

'use strict';

var promiseTimeout = require('promise-timeout');
var requestPromise = require('request-promise');

promiseTimeout.timeout(requestPromise("http://example.com/prpr"), 10000)
  .then(function (result) {
    console.log({result});
  }).catch(function (err) {
    if (err instanceof pt.TimeoutError) {
      console.error('HTTP get timed out');
    }
  });

关于javascript - 如果代码需要很长时间才能完成,如何在 node.js 中引发超时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51856324/

相关文章:

javascript - 读取存储在 SharePoint 列表中的用户

node.js - Node http get请求无法处理希伯来语内容

javascript - 启动后我如何在 Node webkit中获取窗口对象

node.js - pidfile存在,但进程已死

javascript - 文本未显示在移动 View 中

javascript - 当 mousedown/mouseup 注册时,双击计时器始终为空

javascript - 如何使用 where 子句从 firestore 中删除文档

javascript - 如何在 Hapi.js 的预处理程序中抛出错误

javascript - React object.map 由于 key 而未更新

javascript - 如何在node.js中向特定客户端发送消息