javascript - JS - 中断异步执行
问题描述
实际问题
我要解决的问题是用户可能没有提供足够的消息信息(不和谐)。然后,为了获取所有必要的数据,系统会提示用户对机器人消息做出反应。该机器人消息有 3 个阶段,“InitialPrompt”、“TimeoutWarning”和“TimeoutSuccess(TicketFailure)”。
我想要的解决方案是什么
使用我编写代码的方式,在初始化后无法中止超时。我认为抛出错误会停止函数的执行。我想这不会发生,因为异步调用排队而不是逐行运行。
有没有办法在不添加布尔值并检查每个函数调用的前面的情况下做到这一点?
我能想出的解决方案
const interPtr = {interrupted : false};
interruptSignal(interPtr);
if(interPtr.interrupted) return;
console.log("...");
...
实际代码
(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);
}
})()
解决方案
推荐阅读
- python - 循环中生成的多个(matplotlib)图没有明显更新
- java - 为什么当参数为空时抛出异常不起作用?
- html - 为什么主页按钮也会出现灰色悬停?
- jquery - 带有 jquery 选择值的 django
- ruby - 未初始化的常量 Reform::Form::Errors 更新捆绑器并启动 Rails 服务器后
- reverse-proxy - Quarkus 中的反向代理支持
- save - 使用 Gensim 保存 FastText 自定义模型二进制文件
- tensorflow - 如何从从 TFHub 下载的预训练 word2vec 模型中获取词向量?
- c# - Umbraco 8:SetValue 有一些无效参数 - 将新图像保存到媒体 C#
- php - 在 php nlp 相似性中从用户那里获取输入