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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…