如何为这个异步函数添加超时

How to add timeout to this async function

我想添加一个超时,如果这些“任务”中的任何一个花费的时间超过 5 分钟,它应该停止该功能并解决承诺。我一直在挣扎,感谢任何帮助。谢谢!

if (require.main === module) {
  (async () => {
    const tasks = [];
    for (let i = 1; i <= NB_PARALLEL; i++) {
      tasks.push(buildReferenceSpaceCollection(json));
    }
    const results = await Promise.all(tasks);
    console.log(results);
    process.exit(0);
  })().catch(console.error);
}

您可以定义一个 wait 函数,它在给定的时间后拒绝,然后在该 wait 函数和您的 Promise.all 上使用 Promise.race。现在,如果您在 Promise.all 中的承诺花费的时间比 wait 更长,Promise.race 将拒绝,否则解析的值将分配给 results

function wait(ms) {
    return new Promise((_, reject) => {
        setTimeout(() => {
           reject(new Error("wait time exceeded"));
        }, ms);
    })
}

(async () => {
    const tasks = [];
    for (let i = 1; i <= NB_PARALLEL; i++) {
      tasks.push(buildReferenceSpaceCollection(json));
    }
    // 5 mins in ms
    const wait5MinPromise = wait(5*60*1000);
    const results = await Promise.race([wait5MinPromise, Promise.all(tasks)]);
    console.log(results);
    process.exit(0);
  })().catch(console.error)

;

纯属娱乐 (Live demo):

import { CPromise } from "c-promise2";

const generateYourAsyncTaskHereToAddInQueue= async (value)=> {
    console.log(`Inner task started [${value}]`);
    await CPromise.delay(1000);
    return value;
}

(async () => {
    const results = await CPromise.all(function* () {
        for (let i = 0; i < 10; i++) {
            yield generateYourAsyncTaskHereToAddInQueue(`Task result ${i}`);
        }
    }, {concurrency: 3}).timeout(5000);

    console.log(`results:`, results);

    return results;
})().catch(console.error);