Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support timeout for request #15

Open
haquezameer opened this issue Mar 4, 2021 · 3 comments
Open

Support timeout for request #15

haquezameer opened this issue Mar 4, 2021 · 3 comments
Labels
enhancement New feature or request help wanted Extra attention is needed

Comments

@haquezameer
Copy link

haquezameer commented Mar 4, 2021

With the current system, a req is retried infinitely until we get a success response. Accepting a timeout would be good to break the loop of retrying.

Faced this recently when writing a few jest tests, where I wanted the request to succeed but only wait for a certain time and let the request timeout after that.

Something like this?

    const main = () => {
      const request = http.request(
        { method, port: options.port, path: options.path, timeout: 5000 },
        (response) => {
          if (response.statusCode === 200) {
            return resolve({ started: true });
          }

          return main();
        },
      );

      request.on('error', main);
      request.on('timeout', () => {
        request.destroy();
        return resolve({ started: false });
      });
      request.end();
    };

    main();
@sindresorhus
Copy link
Owner

Sure. That sounds useful.

@sindresorhus sindresorhus added enhancement New feature or request help wanted Extra attention is needed labels Mar 4, 2021
@haquezameer
Copy link
Author

@sindresorhus
what do you think about the resolved value of { started: true/false }?. While it may not be useful for everyone, this came in handy when people want to explicitly assert whether request succeeded/failed, especially when using the timeout.

@sindresorhus
Copy link
Owner

I think it should rather reject the promise when it times out.

Should use a custom error, like done here: https://github.com/sindresorhus/p-timeout/blob/4f86930f75d1565927790ab70b4ac643e47007fc/index.js#L3-L8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants