Promise batch progress meter in TypeScript

Nodejs has a handy Promise.all function that awaits an entire batch of promises. However, sometimes you want to see how that batch of promises is progressing before the whole thing has finished.

Here’s a rough-and-ready way to print a progress meter to stdout as a batch of promises completes in TypeScript:

const promises = [1, 2, 3, 4, 5].map(async (i: number): Promise<string> => {
    return 'finished some work'
})

let finishedCount = 0
promises.forEach((promise: Promise<string>): void => {
    promise.then((): void => {
        finishedCount++
        process.stdout.clearLine()
        process.stdout.cursorTo(0)
        process.stdout.write(`${finishedCount} / ${promises.length}`)
    }).catch(() => {
        // Handle errors.
    })
})

await Promise.all(promises)

That just prints and updates a line like 3 / 5 to stdout. You could make it fancier with a percentage or a visual progress meter.


Tech mentioned