Promise for request/response with timeout Below is a piece of code that uses a promise for sending a request to a server, and to wait for an answer. Under normal conditions the server will always respond immediately, 

But of course you don't want your code to be stuck forever if a response is missed (e.g. a network issue). So for that reason, it needs a timeout as well.

I usually write this as follows. But it takes quiet a lot of code. Any sugestions ?

new Promise( (resolve, reject) =&gt; {
  // the promise is resolved when a predefined response is received.
  const listener = (msg) =&gt; {
    const { command } = msg;
    if (command === "pong") resolve();
  };

  try {
    this.addListener(listener);

    // write the command
    this.sendMessage( { command: "ping" });

    // there should be an answer within x seconds
    await new Promise(() =&gt; setTimeout(reject, timeout));
  }
  finally {
    this.removeListener(listener);
  }
}


I have been using this as a pattern for nodejs, angular and react code.
await is only applicable in async functions. The executor function passed to Promise constructor at the code at the question is not defined as async. 

The second Promise constructor is not necessary. resolve and reject defined at the single Promise executor can be used.

Include .catch() or function at second parameter of .then() chained to Promise constructor to avoid Uncaught in Promise error and handle potential error within Promise constructor function body.

new Promise((resolve, reject) =&gt; {
  try {
    const complete = () =&gt; !clearTimeout(time) 
      &amp;&amp; this.removeListener(listener);
    const listener = ({command}) =&gt; command === "pong" 
      &amp;&amp; !complete() &amp;&amp; resolve();
    this.addListener(listener);
    this.sendMessage({ command: "ping" });
    const time = setTimeout(() =&gt; !complete() &amp;&amp; reject(), timeout);
  } catch (e) {
      throw e
  }
})
// handle resolved `Promise`, handle error
.then(() =&gt; {}, e =&gt; console.error(e));