Mar1009
Mar1009

Reputation: 811

How can I return a error if response not received in 1 minute (NodeJs)

First thing to note I'm using node version of 6.15.

Here I have a promise method which will return response upon calling an function.

myFunction: (params) = {
return innerFunction(params)
    .then((resp) => {
      return resp })
    .catch((err) => { 
       throw err })
}

Here the challenge is innerFunction sometime will take more time to give response, so I need to return this function as an error if response doesn't received in 1 minute

How can I achieve that?

Upvotes: 0

Views: 283

Answers (2)

Roamer-1888
Roamer-1888

Reputation: 19288

This is simply achieved with static method Promise.race(). All you have to do is race the promise returned by innerFunction() against a promisified timeout that settles to an Error.

  • if innerFunction() wins the race, then its result/Error will be delivered.
  • if the promisified timeout wins the race, then its Error will be delivered.

In other words, Promise.race() is transparent to whichever promise wins the race and opaque to the other.

myFunction: (params) = {
    let timeoutPromise = new Promise((_, reject) => {
        setTimeout(reject, 60000, new Error('timed out'));
    });
    return Promise.race([timeoutPromise, innerFunction(params)]); // race two promises against each other.
}

For flexibility, you might choose to pass the timeout duration to the function, and allow a zero value to mean no timeout.

myFunction: (params, timeoutDuration = 0) = {
    if(timeoutDuration > 0) {
        let timeoutPromise = new Promise((_, reject) => {
            setTimeout(reject, timeoutDuration, new Error('timed out'));
        });
        return Promise.race([timeoutPromise, innerFunction(params)]); // race two promises against each other.
    } else {
        return innerFunction(params);
    }
}

Upvotes: 1

csakbalint
csakbalint

Reputation: 786

For a simple solution, I would use the bluebird#timeout method! (more about this here)

Here is a short example, how to use it:

// import the library
const Bluebird = require('bluebird') 

// timeout needs the duration parameter in milliseconds
const TIMEOUT_IN_MS = 60000; // 1 min

// if you use the native promise, you must wrap it first
// it returns a promise compatible with the native promise
Promise.resolve(innerFunction(params)).timeout(TIMEOUT_IN_MS)

Upvotes: 0

Related Questions