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) => {
// the promise is resolved when a predefined response is received.
const listener = (msg) => {
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(() => setTimeout(reject, timeout));
}
finally {
this.removeListener(listener);
}
}
I have been using this as a pattern for nodejs, angular and react code.