title: How to cancel http request properly in Node.js?
body: <p>I need to implement a cancel-able client-side HTTP request in Node.js, without using external libraries. I'm giving a <code>Promise</code> object - <code>cancellationPromise</code> - which gets rejected when the cancellation is externally requested. This is how I know I may need to call <code>request.abort()</code>. </p>
  
  <p><strong>The question is, should I be calling <code>request.abort()</code> only if <code>https.request</code> is still pending and <code>response</code> object is not yet available?</strong> </p>
  
  <p>Or, should I be calling it even if I already got the <code>response</code> object and am processing the response data, like in the code below? In which case, will that stop any more <code>response.on('data')</code> events from coming?</p>
  
  <pre><code>  async simpleHttpRequest(url, oauthToken, cancellationPromise) {
      let cancelled = null;
      let oncancel = null;
  
      cancellationPromise.catch(error =&gt; { 
        cancelled = error; oncancel &amp;&amp; oncancel(error) });
  
      try {
        const response = await new Promise((resolve, reject) =&gt; {
          const request = https.request(
            url.toString(), 
            { 
              method: 'GET', 
              headers: { 'Authorization': `Bearer ${oauthToken}` }        
            }, 
            resolve);
  
          oncancel = error =&gt; request.abort();
          request.on('error', reject);
          request.end();
        });
  
        if (cancelled) throw cancelled;
  
        // do I need "oncancel = null" here?
        // or should I still allow to call request.abort() while fetching the response's data?
  
        // oncancel = null;
  
        try {
          // read the response 
          const chunks = await new Promise((resolve, reject) =&gt; {
            response.on('error', reject);  
            const chunks = [];
            response.on('data', data =&gt; chunks.push(data));
            response.on('end', () =&gt; resolve(chunks));
          });
  
          if (cancelled) throw cancelled;
          const data = JSON.parse(chunks.join(''));
          return data;
        }
        finally {
          response.resume();
        }
      }
      finally {
        oncancel = null;
      }
    }
  </code></pre>