0

I have js functions on which I want to apply a timer. so that for some amount of time, the function should execute and after reaching to the set time, the error msg should print like "Time Out".

module.exports.get = function (url) {
    return new Promise(function (resolve, reject) {
        request({
            url: url,
            headers: headers,
        }, function (err, res, body) {
            if (!err && res.statusCode == 200) {
                resolve({
                    status: true,
                    result: JSON.parse(body)
                });
            } else {
                resolve({
                    status: false,
                    result: body
                });
            }
        });
    })
}

Now i want is to execute this function for 20 seconds and if the function executed well and get the response then its fine but if it takes more than 20 seconds then it stop the execution and show message saying "Time Out for the request".

wangdev87
  • 8,611
  • 3
  • 8
  • 31
Lalit Dubey
  • 51
  • 1
  • 9
  • At the start of your promise, use `let tid = setTimeout(...);` to schedule a function that calls `reject({ status: false, error: "timeout" })`. In your request's callback, if successful, simply call `clearTimeout(tid);` –  Nov 18 '20 at 08:49
  • Possible duplicate: [How to set a timeout on a http.request() in Node?](https://stackoverflow.com/questions/6214902/how-to-set-a-timeout-on-a-http-request-in-node) –  Nov 18 '20 at 08:50
  • @ChrisG can you please implement and post the final solution. – Lalit Dubey Nov 18 '20 at 09:15

0 Answers0