Awaiting Loops in Node JS along with Increased Performance (Part 2)

This is an article where I will be explaining a method by which you can write loops that can not only process iterations parallelly, but can also be awaited. Thus combining the good features of forEach loop and for loop together and discarding their shortcomings !

I am talking about a feature in Node JS known as Promise.all

This simple little trick can also be used to improve the overall performance of a NodeJS application by replacing for loops by Promise.All based functions.

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function parllelLoopExample(){
    let xarr = []
    let yarr = [1, 2, 3, 4, 5]
    await Promise.all(
        yarr.map(
            async y => {
 
                await timeout(5000)
                
                console.info('Pushing ' + y + )
                xarr.push("String " + y.toString())
        
            }
        )
    )
    return Promise.resolve(xarr)
}
async function main() {
     let result = await parllelLoopExample()
     console.log(result)
}
 
main()

Which produces the output as –

Pushing 1
Pushing 2
Pushing 3
Pushing 4
Pushing 5
[ 'String 1', 'String 2', 'String 3', 'String 4', 'String 5' ]

Note that how the Promise.all has been used in function parllelLoopExample.

<pre class="wp-block-syntaxhighlighter-code">function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function parllelLoopExample(t){
    let xarr = []
    let yarr = [1, 2, 3, 4, 5]
    await Promise.all(
        yarr.map(
            async y => {
 
                await timeout(5000)
                let hrend = process.hrtime(t)
                console.info('Pushing ' + y + ' at : %ds %dms', hrend[0], hrend[1] / 1000000)
                xarr.push("String " + y.toString())
        
            }
        )
    )
    return Promise.resolve(xarr)
}
async function main() {
console.log("\nExecution Times for Parallel Loops using  Promise.All ---- ")
    var hrStartParllelLoop= process.hrtime()
    console.log(await parllelLoopExample(hrStartParllelLoop))
    let hrEndParallelLoop = process.hrtime(hrStartParllelLoop)
    console.info('Total Execution Time for Parallel Loops using  Promise.All` : %ds %dms', hrEndParallelLoop[0], hrEndParallelLoop[1] / 1000000)
}
main()</pre>

Similar to the examples in my previous article we can perform the execution time analysis to compare it’s performance with them.

Execution Times for Parallel Loops using Promise.All ----
Pushing 1 at : 5s 5.7034ms
Pushing 2 at : 5s 8.4164ms
Pushing 3 at : 5s 9.8981ms
Pushing 4 at : 5s 11.4092ms
Pushing 5 at : 5s 13.201ms
[ 'String 1', 'String 2', 'String 3', 'String 4', 'String 5' ]
Total Execution Time for Parallel Loops using Promise.All` : 5s 22.341899ms

The output of Execution Time Analysis along with the output of the function clearly depicts that it is a winner when it comes to performance as well as the functionality of being awaited!

If you found this article to be helpful share it with your developer buddies so that even they can improve their applications !

0

Leave a Reply