Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

javascript - Handling events with async callbacks

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..

question from:https://stackoverflow.com/questions/65661973/handling-events-with-async-callbacks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...