每个 Promise 的超时不重置

问题描述 投票:0回答:1

我正在尝试让每个地图框单元格都能下载。我希望每个循环都有 60 秒的时间来下载街道地图和卫星地图。无论是否成功不断循环和下载地图,这似乎每 60 秒就会超时。 因此它将循环并正确下载,但每次都会在 60 秒后超时,而不是第一个循环,允许 60 秒,完成,第二个循环重新启动并允许 60 秒,完成...... 下载时间不到 10 秒,因此永远不会超时。我也在登录以查看他们完成情况。

const downloads = bufferedCellBBoxes.map(async (cell, i) => {
    let timeoutResolved = false; // Flag to track if the timeout has already been resolved

    const timeoutPromise = new Promise((resolve) => {
      setTimeout(() => {
        if (!timeoutResolved) {
          resolve('timeout');
          timeoutResolved = true; // Set flag to true to indicate timeout has been resolved
        }
      }, 60000); // 60 seconds timeout
    });

    const satellitePromise = downloadMapTiles(
      'satellite',
      [
        [cell[2] as number, cell[3] as number],
        [cell[0] as number, cell[1] as number],
      ],
    );

    const streetPromise = downloadMapTiles(
      'street',
      [
        [cell[2] as number, cell[3] as number],
        [cell[0] as number, cell[1] as number],
      ],
    );

    return Promise.race([
      Promise.all([satellitePromise, streetPromise]),
      timeoutPromise,
    ])
      .then((result) => {
        // Check if the result is 'timeout', if so, cancel the ongoing processes
        if (result === 'timeout') {
          throw new Error('Timed out');
        }
        return result; // Return the resolved promise result
      })
      .catch((error) => {
        console.error('Error during tile download:', error);
        return Promise.reject(error);
      });
  });
javascript promise
1个回答
0
投票

我很多年前就写了这个函数,但是它对我很有帮助

async function concurrentPromiseAll(items, concurrency, fn) {
    const results = new Array(items.length);
    const queue = items.map((item, index) => ({
        item,
        index,
    }));
    const doFn = async ({ item, index }) => {
        results[index] = await fn(item);
        return queue.length && doFn(queue.shift());
    };
    const slots = queue.splice(0, concurrency).map(doFn);
    await Promise.all(slots);
    return results;
}
const downloads = concurrentPromiseAll(bufferedCellBBoxes, 4, (cell) => {
    // your map callback function here
});
© www.soinside.com 2019 - 2024. All rights reserved.