Search code examples
javascriptpromiseasync-awaites6-promise

Async promises with delay in between starts


I need to build several packages on Jenkins, using Webpack. In my build-script, I use the following:

const builds = [];
packages.forEach(p => builds.push(buildWeb(p).catch(error => console.log(error))));
await Promise.all(builds);

For each package, a promise gets executed in order to build it. However, Promise.all executes all the promises at once, causing a memory heap overflow. I tried executing them one by one, which works fine, but my colleagues asked to implement the following:

Start the first promise, wait for 10 seconds, and start running the second one asynchronously, wait again for 10 seconds to start running the third one, and so on...

I've tried it with setTimeout, but couldn't get it to work.

Is there a wait to execute dynamic promises with a delay between the start of each one?


Solution

  • My suggestion would be to wrap setTimeout into a promise itself and use async/await inside a for loop. Here's an example:

    const delay = (duration) => {
        return new Promise(resolve => {
            setTimeout(() => resolve(), duration);
        });
    }
    
    const main = async () => {
        const builds = [];
    
        for (let p of packages) {
            builds.push(buildWeb(p).catch(error => console.log(error)))
            await delay(10000); // Wait for 10 seconds
        }
    
        await Promise.all(builds);    
    }
    
    main().catch(console.error);