DEV Community

Cover image for Async/await inside loops in JavaScript
Shadid Haque
Shadid Haque

Posted on

10 2

Async/await inside loops in JavaScript

This is a video tutorial based on my earlier post in Dev.to. You can find written tutorial in the link below. Enjoy the video and let me know if you have any feedback.

Written tutorial

Top comments (4)

Collapse
 
yathink3 profile image
yathink3 โ€ข โ€ข Edited

i think best way to achieve this making prototype function and then good to go

Array.prototype.forAsyncSerial = async function (fn = null) {
let result = [];
for (let i = 0; i < this.length; i++) {
if (typeof fn !== 'function') result[i] = await this[i];
else result[i] = await fn(this[i], i);
}
return result;
};

Array.prototype.forAsyncParallel = async function (fn = null) {
if (typeof fn !== 'function') return await Promise.all(this);
else return await Promise.all(this.map(fn));
};

Collapse
 
shadid12 profile image
Shadid Haque โ€ข

Good suggestion. Mind if I use this in the next video :)

Collapse
 
yathink3 profile image
yathink3 โ€ข

Dont forget to mention my name ๐Ÿ˜‰

Thread Thread
 
shadid12 profile image
Shadid Haque โ€ข

absolutely ๐Ÿ˜‰๐Ÿ‘Œ

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

๐Ÿ‘ฅ Ideal for solo developers, teams, and cross-company projects

Learn more