Search code examples
node.jsasynchronouspromisetimeout

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

Solution

  • 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)
    

    ;