Here is my closure that creates a promise that resolves to an object:
function createConnection(host, port, timeout) {
let latestTransactionId = 0;
let commandResolvers = new Map();
const socket = new WebSocket(`${host}:${port}`);
function newTransactionId() {
latestTransactionId += 1;
return latestTransactionId.toString();
}
function request(body) {
return new Promise(function(resolve, reject) {
const transactionId = newTransactionId();
commandResolvers.set(transactionId, resolve);
socket.send(JSON.stringify({
...body,
trans_id: transactionId
}));
setTimeout(function () {
reject(Error("Command timed out..."));
}, timeout);
});
}
return new Promise(function(resolve, reject) {
socket.onopen = function () {
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
const transactionId = data.trans_id;
const commandResolver = commandResolvers.get(transactionId)
commandResolver(data);
};
connection = {
request: request
}
resolve(connection);
};
setTimeout(function () {
reject(Error("Connection timed out..."));
}, timeout);
});
}
Here is how I use it:
const connection = await createConnection(host, port, timeout);
How would I rewrite the object creation implementation to make this syntax possible:
const connection = await new Connection(host, port, timeout);
or maybe the following would be better
const connection = await new ConnectionPromise(host, port, timeout);
And would that make sense? I still have some problem understanding when I should use a closure to create an object and when I should use a prototype. People also seem to recommend different patterns with very little practical advantages and disadvantages, but I just like the prototype pattern more so would prefer to use it here it it makes sense to do so.