Sumanth Jois
Sumanth Jois

Reputation: 97

Axios inside for loop

I am trying to axios requests inside a for loop but the loop is being completed even before the axios. Following is my code:

let findEmail = async() => {
 for (var i = 0; i < csvData.length; i++){
    axios.post('https://email-finder.herokuapp.com/find', {
        "first_name": "Irinaa",
        "last_name": "xyz",
        "domain": "xyxz.com"
    }).then((response) => {
        if(response.status === 500){
            console.log('no email found');
        }
        else{
            console.log(response.data);
        }
    }, (error) => {
        console.log('no email found ', i);
    });
      console.log('axios request done');
 }
} 

I want the loop to wait until the request is complete and then go to increment the i variable. Any help would be much appreciated. Thank you

Upvotes: 1

Views: 2541

Answers (4)

ccali11
ccali11

Reputation: 21

Another pattern to consider: use an array of promises and Promise.all.

For example:

let findEmail = async() => {
 const promises = []
 for (var i = 0; i < csvData.length; i++){
    const request = axios.post('https://email-finder.herokuapp.com/find', {
        "first_name": "Irinaa",
        "last_name": "xyz",
        "domain": "xyxz.com"
    }).then((response) => {
        if(response.status === 500){
            console.log('no email found');
        }
        else {
            console.log(response.data);
        }
    }, (error) => {
        console.log('no email found ', i);
    });
      console.log('axios request done');
      promises.push(request)
 }
await Promise.all(promises)
} 

Upvotes: 0

Anubhav Gupta
Anubhav Gupta

Reputation: 76

As you are in async function try using await instead of then. It will make your for loop behave synchronously.

let findEmail = async () => {
      for (var i = 0; i < csvData.length; i++) {
        try {
          let response = await axios.post(
            "https://email-finder.herokuapp.com/find",
            {
              first_name: "Irinaa",
              last_name: "xyz",
              domain: "xyxz.com"
            }
          );
          if (response.status === 500) {
            console.log("no email found");
          } else {
            console.log(response.data);
          }
        } catch (error) {
          console.log("no email found ", i);
        }
        console.log("axios request done");
      }
    };

Upvotes: 3

Ziv Ben-Or
Ziv Ben-Or

Reputation: 1194

If you are waiting to get data back, so you are waiting to status 200. Try to add:

    else if(response.status === 200){
        console.log(response.data);
    }

Upvotes: 0

SELA
SELA

Reputation: 6813

Please find the explanation on How to await an async call in JavaScript in a synchronous function? here by T.J. Crowder.

Upvotes: 0

Related Questions