【问题标题】:Axios inside for loopaxios里面的for循环
【发布时间】:2020-03-30 01:57:13
【问题描述】:

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

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

【问题讨论】:

  • 尝试使用 Promise,如果你擅长使用可以帮助你的可观察对象

标签: javascript for-loop axios


【解决方案1】:

当您在异步函数中时,请尝试使用 await 而不是 then。 它会让你的 for 循环同步运行。

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

【讨论】:

  • 同步和同步行为之间有很大的区别。
  • 伟大的收获。这是我的第一个答案,所以你可以说是菜鸟。
【解决方案2】:

请在 如何在同步函数中等待 JavaScript 中的异步调用? here by T.J. 找到解释。克劳德。

【讨论】:

    【解决方案3】:

    如果您正在等待取回数据,那么您正在等待状态 200。 尝试添加:

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

    【讨论】:

      【解决方案4】:

      要考虑的另一种模式:使用一组 promise 和 Promise.all。

      例如:

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

      【讨论】:

        猜你喜欢
        • 2018-05-21
        • 1970-01-01
        • 2020-03-07
        • 1970-01-01
        • 2019-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多