【问题标题】:How to promise.race an array of async callbacks vs a timeout如何 promise.race 一组异步回调与超时
【发布时间】: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: () =&gt; Promise&lt;void&gt;不是问题中的代码。在问题的代码中,cb 的类型将是 cb: (async: any) =&gt; number(在浏览器上)。这些不是async 函数。 (Related question.)请用minimal reproducible example 来展示问题,最好是可运行一个使用 Stack Snippets([&lt;&gt;] 工具栏按钮); here's how to do one

标签: javascript typescript


【解决方案1】:

你的closeCallbacks 不是异步的,你需要他们返回一个promise

const closeCallbacks = [
  // for sample purposes. i assigned timeouts to mock that it takes longer to run these callbacks then my timeout duration
  async () => new Promise(resolve => setTimeout(() => resolve(console.log('cb1')), 3000)),
  async () => new Promise(resolve => setTimeout(() => resolve(console.log('cb2')), 5000)),
];

【讨论】:

    【解决方案2】:

    这将创建一个名为 async 的参数,而不是异步函数

    (async) => {}
    

    你的 timeout 函数从不调用 res 参数

    const wait = (cb, time) => new Promise(r => { cb(); r() }, time)
    
    const closeCallbacks = [
      () => wait(() => console.log('cb1'), 3000),
      () => wait(() => console.log('cb2'), 5000)
    ];
    
    const timeout = new Promise((res) => setTimeout(() => console.log('timeout'); res(), 4000));
    

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 1970-01-01
      • 2020-12-08
      • 2017-07-24
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多