admin管理员组文章数量:1296254
Is the following somehow possible?
async function doesSocketAgree(){
socket.emit('doesOtherSocketAgree', otherSocketId);
await socket.on('responseDoesSocketAgree', (answer)=>{
console.log('answer');
});
}
Is the following somehow possible?
async function doesSocketAgree(){
socket.emit('doesOtherSocketAgree', otherSocketId);
await socket.on('responseDoesSocketAgree', (answer)=>{
console.log('answer');
});
}
Share
Improve this question
asked Feb 17, 2020 at 23:58
Julian HackenbergJulian Hackenberg
1232 silver badges6 bronze badges
2 Answers
Reset to default 6In socket.io you can use "acknowledgements" callbacks:
async function doesSocketAgree(){
await new Promise(resolve => {
socket.emit('doesOtherSocketAgree', otherSocketId, (answer) => {
resolve(answer);
});
});
}
https://socket.io/docs/#Sending-and-getting-data-acknowledgements
So you can use a single emit()
and can trigger a callback.
That has the advantage you dont have to deal with memory leaks from register an event listener every time you call this function.
It is, but not that way. You'll have to wrap things in a promise so that you can "return" from your await
once data es in as part of your "on" handling:
async function doesSocketAgree(){
socket.emit('doesOtherSocketAgree', otherSocketId);
await new Promise(resolve => {
socket.on('responseDoesSocketAgree', answer => {
resolve(answer);
});
});
}
And you probably want to remove that listener before you call resolve()
so that it doesn't keep on triggering, because every time you call doesSocketAgree()
you'd be adding a new listener to the "on:responseSocketAgree" pile. So that'll end up going wrong pretty quickly without cleanup.
On that note, you probably want to emit your "does it agree?" with a random token that your on
handler can verify is the one that's scoped to the current function call, "because async".
本文标签: javascriptAwait socketon(39answerToRequest39) possible with SocketioStack Overflow
版权声明:本文标题:javascript - Await socket.on('answerToRequest') possible with Socket.io? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741634523a2389563.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论