首页 > 解决方案 > JS - 中断异步执行

问题描述

实际问题

我要解决的问题是用户可能没有提供足够的消息信息(不和谐)。然后,为了获取所有必要的数据,系统会提示用户对机器人消息做出反应。该机器人消息有 3 个阶段,“InitialPrompt”、“TimeoutWarning”和“TimeoutSuccess(TicketFailure)”。

我想要的解决方案是什么

使用我编写代码的方式,在初始化后无法中止超时。我认为抛出错误会停止函数的执行。我想这不会发生,因为异步调用排队而不是逐行运行。

有没有办法在不添加布尔值并检查每个函数调用的前面的情况下做到这一点?

我能想出的解决方案

const interPtr = {interrupted : false};
interruptSignal(interPtr);

if(interPtr.interrupted) return;
console.log("...");
...

实际代码

JS小提琴

(async () => {
  const sleep = async time => new Promise(resolve => setTimeout(resolve, time));

  const interruptSignal = () => new Promise(async (res, rej) => {
    console.log("interruptStarted")
    await sleep(2000);
    console.log("interruptRan");
    throw "Interrupted"
  });
  

  const timeOutHandler = async () => {
    interruptSignal();
    console.log("TimeoutStarted")
    await sleep(5000);
    console.log("TimeoutWarning")
    await sleep(5000);
    console.log("TimeoutSuccess->TicketFailure")
  };

  try {
    await timeOutHandler();
  } catch (e) {
    console.log(e);
  }
  
})()

标签: javascriptasynchronousasync-awaitcancellation

解决方案


推荐阅读