Reputation: 947
How can I use async/await or another technique to use async callbacks in a message handler? Messages can come at any time so while one message is being handled in a async function, another message could come in and be handled faster. This is a problem if the order of messages matters.
socket.on('message', async (msg) => {
if(msg === 1){
await doFirstThing();
}
else if (msg === 2){
await doSecondThing();
}
});
If doFirstThing()
takes a while, the message for doSecondThing()
may come in and be handled too quickly. I was thinking to add to an array and then promise it, but I can't figure out how to push another promise on to the "stack" so to speak if another promises (or more) is pending..
Upvotes: 1
Views: 450
Reputation: 370729
You can have a persistent outer Promise variable that you reassign every time a new message occurs to ensure the proper order.
let prom = Promise.resolve();
socket.on('message', (msg) => {
prom = prom.then(() => {
if(msg === 1){
return doFirstThing(); // return the Promise instead of `await`
} else if (msg === 2){
return doSecondThing();
}
}).catch(handleErrors); // make sure to include this
});
You need to be able to chain onto the Promise indefinitely, so there must never be any rejections of prom
- the .catch
is essential.
Every time a message comes, it'll wait for the last message to be finished handling before the new .then
callback runs.
Upvotes: 3