ecmascript 6 – Request / response promise with waiting time

Below is a snippet of code that uses a promise to send a request to a server, and to wait for an answer. Under normal conditions the server will always respond immediately,

But, of course, you do not want your code to be blocked forever if a response is lost (for example, a network problem). So for that reason, you need a waiting time as well.

I usually write this in the following way. But it takes a lot of code. Any suggestions?

New promise ((solve, reject) => {
// the promise is resolved when a predefined response is received.
listener of const = (msg) => {
const {command} = msg;
if (command === "pong") solve ();

try {
this.addListener (listener);

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

// there must be an answer within x seconds
wait for new Promise (() => setTimeout (rejection, waiting time));
Finally {
this.removeListener (listener);

I've been using this as a pattern for nodejs, angular and react codes.