Await socket Response
I wrote this to make the "callback hell" more manageable on the part of the coder when using Socket IO, so that there wasn't really any callback hell to go with, just a simple await.
This should work with any socket implementation, so long as it has socket.on, socket.emit, and socket.removeListener.
function emit_and_wait(socket, emit, data, wait_key, max_wait = 1000, error_on_timeout = true) {
return new Promise(function(resolve, reject) {
let responded = false,
callback,
removed = false;
if(!socket) {
reject("Socket supplied is not valid.")
} else if(socket.disconnected) {
reject("Socket is disconnected");
}
let timeout = setTimeout(function() {
if(!responded) {
if(error_on_timeout) {
reject("Socket timeout");
} else {
resolve(null);
}
responded = true;
if(!removed) {
socket.removeListener(wait_key, callback);
removed = true;
}
}
}, max_wait)
callback = function(data) {
if(!removed) {
socket.removeListener(wait_key, callback);
}
if(!responded) {
resolve(data);
clearTimeout(timeout);
}
}
socket.on(wait_key, callback);
socket.emit(emit, data)
})
}
javascript asynchronous socket async-await socket.io
add a comment |
I wrote this to make the "callback hell" more manageable on the part of the coder when using Socket IO, so that there wasn't really any callback hell to go with, just a simple await.
This should work with any socket implementation, so long as it has socket.on, socket.emit, and socket.removeListener.
function emit_and_wait(socket, emit, data, wait_key, max_wait = 1000, error_on_timeout = true) {
return new Promise(function(resolve, reject) {
let responded = false,
callback,
removed = false;
if(!socket) {
reject("Socket supplied is not valid.")
} else if(socket.disconnected) {
reject("Socket is disconnected");
}
let timeout = setTimeout(function() {
if(!responded) {
if(error_on_timeout) {
reject("Socket timeout");
} else {
resolve(null);
}
responded = true;
if(!removed) {
socket.removeListener(wait_key, callback);
removed = true;
}
}
}, max_wait)
callback = function(data) {
if(!removed) {
socket.removeListener(wait_key, callback);
}
if(!responded) {
resolve(data);
clearTimeout(timeout);
}
}
socket.on(wait_key, callback);
socket.emit(emit, data)
})
}
javascript asynchronous socket async-await socket.io
add a comment |
I wrote this to make the "callback hell" more manageable on the part of the coder when using Socket IO, so that there wasn't really any callback hell to go with, just a simple await.
This should work with any socket implementation, so long as it has socket.on, socket.emit, and socket.removeListener.
function emit_and_wait(socket, emit, data, wait_key, max_wait = 1000, error_on_timeout = true) {
return new Promise(function(resolve, reject) {
let responded = false,
callback,
removed = false;
if(!socket) {
reject("Socket supplied is not valid.")
} else if(socket.disconnected) {
reject("Socket is disconnected");
}
let timeout = setTimeout(function() {
if(!responded) {
if(error_on_timeout) {
reject("Socket timeout");
} else {
resolve(null);
}
responded = true;
if(!removed) {
socket.removeListener(wait_key, callback);
removed = true;
}
}
}, max_wait)
callback = function(data) {
if(!removed) {
socket.removeListener(wait_key, callback);
}
if(!responded) {
resolve(data);
clearTimeout(timeout);
}
}
socket.on(wait_key, callback);
socket.emit(emit, data)
})
}
javascript asynchronous socket async-await socket.io
I wrote this to make the "callback hell" more manageable on the part of the coder when using Socket IO, so that there wasn't really any callback hell to go with, just a simple await.
This should work with any socket implementation, so long as it has socket.on, socket.emit, and socket.removeListener.
function emit_and_wait(socket, emit, data, wait_key, max_wait = 1000, error_on_timeout = true) {
return new Promise(function(resolve, reject) {
let responded = false,
callback,
removed = false;
if(!socket) {
reject("Socket supplied is not valid.")
} else if(socket.disconnected) {
reject("Socket is disconnected");
}
let timeout = setTimeout(function() {
if(!responded) {
if(error_on_timeout) {
reject("Socket timeout");
} else {
resolve(null);
}
responded = true;
if(!removed) {
socket.removeListener(wait_key, callback);
removed = true;
}
}
}, max_wait)
callback = function(data) {
if(!removed) {
socket.removeListener(wait_key, callback);
}
if(!responded) {
resolve(data);
clearTimeout(timeout);
}
}
socket.on(wait_key, callback);
socket.emit(emit, data)
})
}
javascript asynchronous socket async-await socket.io
javascript asynchronous socket async-await socket.io
edited yesterday
FreezePhoenix
asked 2 days ago
FreezePhoenixFreezePhoenix
581324
581324
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
You have a few flags (removed, responded) which are almost equivalent and possibly useless. removeListener() won't cause any error if listener has been already removed then removed is unnecessary. After you called removeListener() your callback won't be called then also responded (which BTW is a misleading name) is unnecessary. Also, setTimeout() won't call its callback twice then again responded isn't necessary.
Use const instead of let whenever possible and declare your variables (usually one per line) when you initialize them. In (untested) code:
if (!socket) {
reject("Socket supplied is not valid.");
return;
}
if (socket.disconnected) {
reject("Socket is disconnected");
return;
}
const timeout = setTimeout(() => {
socket.removeListener(wait_key, callback);
if (error_on_timeout) {
reject("Socket timeout");
} else {
resolve(null);
}
}, max_wait)
const callback = (data) => {
clearTimeout(timeout);
socket.removeListener(wait_key, callback);
resolve(data);
};
socket.on(wait_key, callback);
socket.emit(emit, data)
Few more notes: resolve() and reject() won't stop execution then you need to add the proper return. Use semicolon consistently: someone prefers to avoid semicolon as much as possible, pick a style and use it consistently.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211117%2fawait-socket-response%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You have a few flags (removed, responded) which are almost equivalent and possibly useless. removeListener() won't cause any error if listener has been already removed then removed is unnecessary. After you called removeListener() your callback won't be called then also responded (which BTW is a misleading name) is unnecessary. Also, setTimeout() won't call its callback twice then again responded isn't necessary.
Use const instead of let whenever possible and declare your variables (usually one per line) when you initialize them. In (untested) code:
if (!socket) {
reject("Socket supplied is not valid.");
return;
}
if (socket.disconnected) {
reject("Socket is disconnected");
return;
}
const timeout = setTimeout(() => {
socket.removeListener(wait_key, callback);
if (error_on_timeout) {
reject("Socket timeout");
} else {
resolve(null);
}
}, max_wait)
const callback = (data) => {
clearTimeout(timeout);
socket.removeListener(wait_key, callback);
resolve(data);
};
socket.on(wait_key, callback);
socket.emit(emit, data)
Few more notes: resolve() and reject() won't stop execution then you need to add the proper return. Use semicolon consistently: someone prefers to avoid semicolon as much as possible, pick a style and use it consistently.
add a comment |
You have a few flags (removed, responded) which are almost equivalent and possibly useless. removeListener() won't cause any error if listener has been already removed then removed is unnecessary. After you called removeListener() your callback won't be called then also responded (which BTW is a misleading name) is unnecessary. Also, setTimeout() won't call its callback twice then again responded isn't necessary.
Use const instead of let whenever possible and declare your variables (usually one per line) when you initialize them. In (untested) code:
if (!socket) {
reject("Socket supplied is not valid.");
return;
}
if (socket.disconnected) {
reject("Socket is disconnected");
return;
}
const timeout = setTimeout(() => {
socket.removeListener(wait_key, callback);
if (error_on_timeout) {
reject("Socket timeout");
} else {
resolve(null);
}
}, max_wait)
const callback = (data) => {
clearTimeout(timeout);
socket.removeListener(wait_key, callback);
resolve(data);
};
socket.on(wait_key, callback);
socket.emit(emit, data)
Few more notes: resolve() and reject() won't stop execution then you need to add the proper return. Use semicolon consistently: someone prefers to avoid semicolon as much as possible, pick a style and use it consistently.
add a comment |
You have a few flags (removed, responded) which are almost equivalent and possibly useless. removeListener() won't cause any error if listener has been already removed then removed is unnecessary. After you called removeListener() your callback won't be called then also responded (which BTW is a misleading name) is unnecessary. Also, setTimeout() won't call its callback twice then again responded isn't necessary.
Use const instead of let whenever possible and declare your variables (usually one per line) when you initialize them. In (untested) code:
if (!socket) {
reject("Socket supplied is not valid.");
return;
}
if (socket.disconnected) {
reject("Socket is disconnected");
return;
}
const timeout = setTimeout(() => {
socket.removeListener(wait_key, callback);
if (error_on_timeout) {
reject("Socket timeout");
} else {
resolve(null);
}
}, max_wait)
const callback = (data) => {
clearTimeout(timeout);
socket.removeListener(wait_key, callback);
resolve(data);
};
socket.on(wait_key, callback);
socket.emit(emit, data)
Few more notes: resolve() and reject() won't stop execution then you need to add the proper return. Use semicolon consistently: someone prefers to avoid semicolon as much as possible, pick a style and use it consistently.
You have a few flags (removed, responded) which are almost equivalent and possibly useless. removeListener() won't cause any error if listener has been already removed then removed is unnecessary. After you called removeListener() your callback won't be called then also responded (which BTW is a misleading name) is unnecessary. Also, setTimeout() won't call its callback twice then again responded isn't necessary.
Use const instead of let whenever possible and declare your variables (usually one per line) when you initialize them. In (untested) code:
if (!socket) {
reject("Socket supplied is not valid.");
return;
}
if (socket.disconnected) {
reject("Socket is disconnected");
return;
}
const timeout = setTimeout(() => {
socket.removeListener(wait_key, callback);
if (error_on_timeout) {
reject("Socket timeout");
} else {
resolve(null);
}
}, max_wait)
const callback = (data) => {
clearTimeout(timeout);
socket.removeListener(wait_key, callback);
resolve(data);
};
socket.on(wait_key, callback);
socket.emit(emit, data)
Few more notes: resolve() and reject() won't stop execution then you need to add the proper return. Use semicolon consistently: someone prefers to avoid semicolon as much as possible, pick a style and use it consistently.
answered yesterday
Adriano RepettiAdriano Repetti
9,73911441
9,73911441
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211117%2fawait-socket-response%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown