JS:执行事件在另一个时间上重叠 [英] JS: Executing events overlapping in time afteranother
问题描述
我以正确的顺序即时接收事件,这些事件要依次处理(以及即时-因此不要先存储"事件).
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).
下面的示例无法正常工作,因为函数 someEventOccured()
可以在非常短的时间内被多次调用.因此,handleEvent的执行将在时间上重叠(我不希望如此).当我在 handleEvent()
中写入文件时,我不能同时执行该功能,而需要保持顺序...
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);
}
我已经尝试过使用.then()并存储promise,但是我不知道如何等待上一个.then()完成...
I have already tried using .then() and storing the promise, however I have no idea how to wait for the previous .then() to finish...
非常感谢您的帮助< 3
Your help is very appreciated <3
推荐答案
一般方法是让一个共享的诺言排队:
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
// …
});
}
当然,这确实将 data
事件隐式存储在promise链的闭包中.
Of course, this does implicitly store the data
events in the closures on the promise chain.
这篇关于JS:执行事件在另一个时间上重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!