【发布时间】:2022-11-12 19:49:41
【问题描述】:
在我关闭我的网络应用程序之前,我有一组可能在不同持续时间上运行的回调。我也有一个超时,如果它超过了超时持续时间,我也会关闭应用程序。这样做的原因是为了防止回调在超过超时持续时间时阻止关闭 Web 应用程序。
这是我目前的解决方案:
const closeCallbacks = [
// for sample purposes. i assigned timeouts to mock that it takes longer to run these callbacks then my timeout duration. In the real world scenario, these are not timeouts but ordinary functions that I want to run but may take time to run
(async) => setTimeout(() => console.log('cb1'), 3000),
(async) => setTimeout(() => console.log('cb2'), 5000)
];
// For some context `cb: () => Promise<void>`
const callbacks = closeCallbacks.map((cb) => cb());
const timeout = new Promise((res) => setTimeout(() => console.log('timeout'), 4000));
Promise.race([Promise.all(callbacks), timeout]).then((data) => {
// Instantly returns Promise.all(callbacks) even if timeout is still in the process of doing there thing
console.log(data)
executeClose();
});
我当前的解决方案是返回Promise.all(callbacks),即使它还没有调用预期的回调来运行。我期望发生的是它通过我的timeout 而不是因为它的计时器为 4000,而最后一个 closeCallback 的计时器为 5000。
我究竟做错了什么?
【问题讨论】:
-
“对于某些上下文
cb: () => Promise<void>”不是问题中的代码。在问题的代码中,cb的类型将是cb: (async: any) => number(在浏览器上)。这些不是async函数。 (Related question.)请用minimal reproducible example 来展示问题,最好是可运行一个使用 Stack Snippets([<>]工具栏按钮); here's how to do one。
标签: javascript typescript