'Timeout doesn't work for request made with node.js

I hope everyone is well.

I have the following code that brings the value of a json:


const https = require('https');
var http = require("https");
var AWS = require('aws-sdk');


exports.handler = async (event, context, callback) => {
    console.log('Event: ', JSON.stringify(event, null, 2));
    const request = event.Records[0].cf.request;



const https = require('https');
const http_get = require('https');

var options = {
    host: 'www.local.dev',
    method: 'GET',
    timeout: 2000,
    path: '/list.json',
    headers: {
        'Accept': 'application/json'
    }
};



const res = await new Promise(resolve => {
  http_get.get(options, resolve);
});


let data = await new Promise((resolve, reject) => {
  let data = '';
  res.on('data', chunk => data += chunk);
  res.on('error', err => reject(err));
  res.on('end', () => resolve(data));
});

data = JSON.parse(data)

// CONTINUE FUNCTION 

    return request;
};

I would like to set a timeout, If the request does not return in 2 seconds, I continue the function, The function has other parts, so even if nothing comes from the json endpoint it can continue.

It has no dependency on the json return.

What is happening and that the timeout is not validated and the function is running indefinitely.

I need to use this http module from node.js, I can't use axios here.

To simulate the timeout I am using this app: httpstat.us/501?sleep=60000



Solution 1:[1]

Change this code

const res = await new Promise(resolve => {
  http_get.get(options, resolve);
});

to this:

const res = http_get.get(options);

https.get returns a stream that is ready to use, and there is no reason to wrap that into a promise (where the syntax you are showing would be incorrect anyway).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GOTO 0