for循环内的axios [英] Axios inside for loop

查看:113
本文介绍了for循环内的axios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 for 循环内执行 axios 请求,但该循环甚至在 axios 之前完成.以下是我的代码:

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 变量.任何帮助将非常感激.谢谢

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

推荐答案

当您使用异步函数时,请尝试使用 await 而不是 then.它将使您的 for 循环同步运行.

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");
      }
    };

这篇关于for循环内的axios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆