Skip to content

Instantly share code, notes, and snippets.

@MrMeison
Created August 7, 2023 19:04
Show Gist options
  • Save MrMeison/43c1f08cdc63b80bf2e663a517f8b498 to your computer and use it in GitHub Desktop.
Save MrMeison/43c1f08cdc63b80bf2e663a517f8b498 to your computer and use it in GitHub Desktop.
const withAcknowledgement = (socketFunc) => (...args) => new Promise((resolve, reject) => {
let state = 'pending'; // eslint-disable-line
const timer = setTimeout(() => {
state = 'rejected';
reject();
}, 3000);
socketFunc(...args, (response) => {
if (state !== 'pending') return;
clearTimeout(timer);
if (response.status === 'ok') {
state = 'resolved';
resolve(response.data);
}
reject();
});
});
const api = {
sendMessage: withAcknowledgement((...args) => socket.volatile.emit('newMessage', ...args)),
createChannel: withAcknowledgement((...args) => socket.volatile.emit('newChannel', ...args)),
renameChannel: withAcknowledgement((...args) => socket.volatile.emit('renameChannel', ...args)),
removeChannel: withAcknowledgement((...args) => socket.volatile.emit('removeChannel', ...args)),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment