title: How to return a rejected promise when it takes the function too long to return a response by itself in Node?
body: <p>I made a back-end in Node.js.</p>
  <p>The back-end contains a function named algorithm.make(). This function has a promise as return type.
  Sometimes the application needs three seconds to fully execute the algoritm.make function and sometimes it needs ten minutes.</p>
  <p>I would like to always return a response (a resolved or rejected promise) after a specific amount of seconds.</p>
  <p>I tried:</p>
  <pre><code>....
  
  try {
         return await Promise.race([
             this.wait(4000),
             algorithm.make()
         ]);
  } catch(err) {
          console.log(err);
  }
  </code></pre>
  <p>Wait function:</p>
  <pre><code>static wait(ms) {
      return new Promise((_, reject) =&gt; {
          setTimeout(() =&gt; reject(new Error('timeout succeeded ' + ms)), ms);
      });
  }
  </code></pre>
  <p>With this code the algorithm.make() will just fully execute (and it will not be stopped after 4000ms).</p>
  <p>But when I do this, it will return a rejected promise after 2 seconds:</p>
  <pre><code>try {
         return await Promise.race([
             this.wait(4000),
             this.wait(2000),
         ]);
  } catch(err) {
          console.log(err);
  }
  </code></pre>
  <p>I don't know why it is working with two setTimeouts but not with one setTimeout and one real function.</p>