DEV Community

GaneshMani
GaneshMani

Posted on • Originally published at cloudnweb.dev

Promises inside a loop - Javascript ES6

In this article, we will see how to write a promise function inside a loop. Promises inside a loop - Javascript ES6

If you want to learn more about Javascript. check out this articles

Prototypal Inheritance - Javascript Weekly

Understanding Closures in Javascript - Javascript Weekly

Configuring Babel for Node/Express

Subscribe to my newsletter for further updates .

Before jumping into the code, we will see why we need to write a promise function inside a loop.

Scenario

Consider a situation where you need to send mail to list of emails. you will write a function which can send a single email at once.

Let's say that you have a list of emails like this

const emailList = ['ganesh@gmail.com','john@gmail.com','tarry@gmail.com']

Firstly, you write a single function which takes an emailId and send a mail to the corresponding mail.

function sendMail() {
  //Sending mail
}

you need to call the function as per the count of emails you have in the array.

you can think of, why can't I call the function inside the for a loop. it will be simple ..right??.

No... that's not going to work. because sending a mail is an asynchronous function. Loop will not wait until the previous function completes

So, there might be a chance of missing a function call or sending mail. To solve this problem, we need to use Promise.

Promises inside a loop - Javascript ES6

Firstly, write the email sending logic inside a function which returns a Promise.


const sendEmail = (userEmail) => {

  return new Promise(async (resolve,reject) => {
        //this is a mock email send logic
        setTimeout(() => {

            resolve(`Email Sent to ${userEmail}`);
        },3000)

  })
}

call the function inside the Javascript map() function and Promise.all

const  sendEmails = async () => {

    const userEmails = ['ganesh@gmail.com','john@gmail.com','Sam@gmail.com'];

    const status = await Promise.all(userEmails.map(email => sendEmail(email)));

    console.log("Status =>",status);

}

This is one of the ways with which you can call promise inside loops.

To sum up, Promises are one the powerful addition in Javascript ES6.Promises inside a loop - Javascript ES6

In addition, we will see more about Core Concepts of Javascript in upcoming articles. Stay Tuned.

Until then Happy Coding :-)

Top comments (6)

Collapse
 
fratzio profile image
fratzio

I've looked at a lot of resources to help solve my problem with trying to query multiple endpoints and looping through the responses with promises and this is the only one that truly helped! Thank you for this resource. I had been banging my head against the wall for weeks before seeing this. :)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
ganeshmani profile image
GaneshMani

Thank you for the Answer. Correct me if i am wrong. if we put "await" for a function. that function has to return a Promise.

Reference : javascript.info/async-await

Collapse
 
diomalta profile image
Diego Malta

I thought the email function was already asynchronous, you that's right.

Collapse
 
kristijanfistrek profile image
KristijanFištrek

Really nicely explained! 🤘

Collapse
 
ganeshmani profile image
GaneshMani

Thank you!! :-)