如何等待事件所调用的函数的整个过程的完成?

发布于 2025-01-25 09:56:59 字数 81 浏览 4 评论 0原文

我有一个事件触发的函数,即使事件是其他时间触发的,是否有任何方法可以等待该功能的整个过程完成,因此只有在此之后它继续处理其他触发器收到的其他触发器?

I have a function that is triggered by an event, is there any way to wait for the completion of the entire process of this function, even if the event is triggered other times, so that only after that it continues processing the other triggers received?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北座城市 2025-02-01 09:57:00

据我了解,您需要一些队列。您需要将事件推到那里,然后对它们进行处理。也许这样的东西:

const queue = [];

function eventHandler(event) {
  queue.push(event);
  if (queue.length === 1) {
    doTheJob();
  }
}
async function doTheJob() {
  if (queue.length > 0) {
    const event = queue[0]
    // do the job with the "event"
    await work1();
    await work2();
    await workN();
    queue.shift();
    doTheJob();
  }
}

As far as I understood you need some sort of a queue. You need to push events there and process them one by one. Maybe something like this:

const queue = [];

function eventHandler(event) {
  queue.push(event);
  if (queue.length === 1) {
    doTheJob();
  }
}
async function doTheJob() {
  if (queue.length > 0) {
    const event = queue[0]
    // do the job with the "event"
    await work1();
    await work2();
    await workN();
    queue.shift();
    doTheJob();
  }
}
诗酒趁年少 2025-02-01 09:57:00

我设法找到了这样的解决方案:

var time = 1;
// SIMULATES THE ACTIVITIES OF THE EVENT
setInterval(async () => {

  await process();

}, 1000);

// THE PROCESSING THAT OCCURS WHEN THE EVENT IS TRIGGERED
async function process() {

  time += 4000
  const myPromise = await new Promise(async function (myResolve, myReject) {

    setTimeout(async () => {
      console.log(`Process executed`);
      myResolve("Process completed");
    }, time);

  });//End myPromise
  var result = await myPromise;
  time = time - 4000
}

I managed to find a solution like this:

var time = 1;
// SIMULATES THE ACTIVITIES OF THE EVENT
setInterval(async () => {

  await process();

}, 1000);

// THE PROCESSING THAT OCCURS WHEN THE EVENT IS TRIGGERED
async function process() {

  time += 4000
  const myPromise = await new Promise(async function (myResolve, myReject) {

    setTimeout(async () => {
      console.log(`Process executed`);
      myResolve("Process completed");
    }, time);

  });//End myPromise
  var result = await myPromise;
  time = time - 4000
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文