简体   繁体   中英

How to add timeout to this async function

I want to add a timeout such that if any of these "tasks" takes longer than 5 minutes, it should stop that function and resolve the promise. I've been struggling a bit, any help is appreciated. Thanks!

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);
}

You could define a wait -function that rejects after the given amount of time and then use Promise.race on that wait -function and your Promise.all . Now, if your promises inside Promise.all take longer than the wait , Promise.race will reject, otherwise the resolved values will be assigned to 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)

;

Just for fun ( 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM