sindresorhus / wait-for-localhost

Wait for localhost to be ready
MIT License
273 stars 10 forks source link

Support timeout for request #15

Open haquezameer opened 3 years ago

haquezameer commented 3 years ago

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 commented 3 years ago

Sure. That sounds useful.

haquezameer commented 3 years ago

@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 commented 3 years ago

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