JS: Executing events overlapping in time afteranother

自闭症网瘾萝莉.ら 提交于 2021-01-25 04:02:48

问题


I receive events on-the-fly in the correct order in which I want to process them after another (as well on-the-fly - so don't "store" them first).

The following example is not going to work as the function someEventOccured() could be called multiple times in a very close timespan. Thus, the execution of handleEvent would overlap in time (which I don't want). As I am writing to a file in handleEvent() I cannot have simultaneously execute the function and need to maintain the order...

async someEventOccured(data:string){
   await handleEvent(data);
}

I have already tried using .then() and storing the promise, however I have no idea how to wait for the previous .then() to finish...

Your help is very appreciated <3


回答1:


The general approach is to have a shared promise to queue onto:

let queue = Promise.resolve();
function someEventOccured(data:string) {
  queue = queue.then(() => {
    return handleEvent(data);
  }).catch(err => {
    // ensure `queue` is never rejected or it'll stop processing events
    // …
  });
}

Of course, this does implicitly store the data events in the closures on the promise chain.



来源:https://stackoverflow.com/questions/64955564/js-executing-events-overlapping-in-time-afteranother

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!