最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to raise a Timeout Error in node.js if code takes long time to finish? - Stack Overflow

programmeradmin0浏览0评论

in ruby I can:

require 'timeout'

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

it will raise timeout error to avoid code lock, how to do same thing in nodejs, nodejs #setTimeout doesn't fit my need

one case is, when i http.get timeout(for ex, netowrk is unstable), I should set timeout and handle the failed get request, I hope impl #timeout, how should i do?

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

in ruby I can:

require 'timeout'

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

it will raise timeout error to avoid code lock, how to do same thing in nodejs, nodejs #setTimeout doesn't fit my need

one case is, when i http.get timeout(for ex, netowrk is unstable), I should set timeout and handle the failed get request, I hope impl #timeout, how should i do?

try {
  timeout(10, function () {
    http.get("example./prpr")
  })
} catch (e) {
  if (e.message == "timeout") {
    // do smth
  } else {
    throw e
  }
}
Share edited Aug 15, 2018 at 10:09 Kris 20k9 gold badges99 silver badges115 bronze badges asked Aug 15, 2018 at 9:38 chikadancechikadance 4,1977 gold badges47 silver badges87 bronze badges 9
  • 1 can you post the code in which you want to apply the timeout? Node.js in asynchronous, so it won't block the code. – McRist Commented Aug 15, 2018 at 9:44
  • Typically in node.js, you would use a setTimeout() to call a callback and stop future processing of the async operation or reject a promise. The details depends upon your asynchronous operation so we would need to see your specific code you want to add a timeout to. – jfriend00 Commented Aug 15, 2018 at 9:48
  • Well, for the http.get() example you now added, you would probably use the built-in timeout feature. – jfriend00 Commented Aug 15, 2018 at 9:50
  • @jfriend00 I update my code, I need #timeout to interrupt too long http.get – chikadance Commented Aug 15, 2018 at 9:50
  • What is your timeout() function? Did you just make that up? There is no such function in Javascript. Did you mean setTimeout() with arguments in a different order? – jfriend00 Commented Aug 15, 2018 at 9:51
 |  Show 4 more ments

3 Answers 3

Reset to default 1

I had a similar situation with nestJS based on node.js.

When calling an external API, it was a problem that even my service slowed down if it took too long. (If the external api is delayed, my service also had a problem of waiting forever.)

I figured out 2 ways.


First way:

      const result = await axios({
        timeout: 10000,  // error: [AxiosError: timeout of 10000ms exceeded] {  code: 'ECONNABORTED', ...
        ...
      });

Second way: Promise.race()

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race

      // first function
      const callAPI = axios({
        method: "GET",
        url: "http://yourapi",
        headers: {
          ...
        }
      });

      // second function
      const timeoutCheck = (s) => {
        return new Promise(resolve => setTimeout(resolve, s));
      }

      // check delay (first function VS second function)
      const result = await Promise.race([
        callAPI,
        timeoutCheck(10000).then(() => {
          throw new Error("api not responding for more than 10 seconds");
        }),
      ]);

      const { data: { resultCode, resultData } } = result;

You could look into a Promise-based approach here.

Using promises you can pass a function to be executed, and then the standard catch is called if that function raises an exception.

There is a helpful promise-based timeout library on NPM (npm install promise-timeout request-promise), and you could use it in Node something along the lines of...

'use strict';

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

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

You can try this out in your case:

 var request = http.get(options, function (res) {
   // other code goes here
 });

 request.setTimeout( 10000, function( ) {
   // handle timeout here
});
发布评论

评论列表(0)

  1. 暂无评论