javascript - 在 for 循环 VueJS 中同步 API 调用

标签 javascript node.js vue.js asynchronous async-await

我正在尝试在 for loop which each loop having to call a API 内获得同步流。 流程总结如下:

  1. 一个Demo1() function包含 forloop 逐一执行,但是在每个循环中它都会执行一次 API 调用。,
  2. 一个MainFunction()在 for 循环执行后检索并执行最终的 API 调用。

代码中显示了对同一函数的支持 API 调用,并且看起来非常不言自明

代码结构如下:


</script>
...

    async MainFunction() {
          
          if (dataPresent) {
            let clientFieldDetails = await this.Demo1()
              .then(() => {
                //This does the final API call based on the results fetched from for loop  
                this.processFinalAPICall(); 
              })
              .catch(err => {
                console.log("Something went wrong... ", err);
              });
          } else {
            console.log(
              "No data.."
            );
          }
        },
    
        async Demo1() {
          //Traversing around each fieldInfo
          //this.dataPresent.items.forEach(item => {
          //Replacing with normal for loop
           for(item of this.dataPresent.items){
            if (item.model) {
              //Upload item model API Call
              this.uploadItem(item.model)
                .then(response => {
                  //PUT API Call
                  this.putItemModel().then(response => {
                    var result = response.data;
                    //Add itemModel fetched from API response
                    models.push(result);
                    console.log(result)
                  });
                })
                .catch(err => console.log("Axios err: ", err));
            } else {
              //Inside item price details
              console.log("inside item price");
              //API call for fetching price info
              this.getitemPriceInfo(item.id);
            }
          });
        },
    
        getitemPriceInfo(itemid){
            if(itemid){
                //API call for fetching price info
                this.getPriceinEuro(itemid);
                itemsPrice.push(result)
            }
            else{
                this.getPriceWorldWide().then(response => {
                   if(response.data === "item not created") 
                     //Create new item API call
                     this.createNewItem(item.id)
                   else{  
                    var result = response.data;
                    //Fetched  API response for itemsPrice
                    itemsPrice.push(result);
                    console.log(result);
                    //Update item API call
                    this.updatePriceItem(item.id);
                   }
                  });
            }
        },    

  //EDIT: Adding API call

  async getPriceinEuro(itemId) {
      await this.$axios
        .get("/auth/getEuroPrice", {
          params: {
            itemID: itemId
          }
        })
        .then(response => {
          console.log(" Resp :" + response.data);
          let result = response.data;
          //This gives me the price
         itemsPrice.push(result)
        });
    },
       
    
        processFinalAPICall(){
            //get itemsPrice and models price pushed
            var apiBodyModel = []; 
            this.models.forEach(model=>{
               var uri = {
                   url: /modelInfo/+model
               }
              apiBodyModel.push(uri)  
            })
    
            var apiBodyPrice = []; 
            this.itemsPrice.forEach(price=>{
               var uri = {
                   url: /priceInfo/+price
               }
              apiBodyPrice.push(uri)  
            })
            //Create a post body request from above data and POST
            ....
        }
 ...
</script>

代码当前在 for 循环中循环,不等待 API 调用完成。它首先执行 processFinalCall(),然后执行 API 调用。我不确定async/await ,如果我用错了请原谅。我如何让forLoop首先执行,然后启动processFinalAPICall()来自主函数?

请告诉我我的做法是否正确。谢谢:)

我使用的是 Node 版本 8.11由于我们的项目依赖性。

已编辑: 添加了 API 函数调用以供引用

最佳答案

我相当确定您遇到的问题在于您的 Demo1 函数,从广义上讲,该函数如下所示:

async Demo1() {
  [ARRAY OF ITEMS].forEach(item => {
    this.uploadItem(item)
      .then(response => {
        // do some stuff
      });
    .catch(err => /* log errors */);
  });
}

您不会在此处等待上传,因此当您在MainFunction()中调用Demo1()时,它会通过上传,无需等待上一个先完成。我认为解决这个问题的最简单方法是使用 for-of 循​​环,因为您将函数传递给 .forEach,这只会让事情变得复杂。

因此,您可以这样做,而不是 [ARRAY OF ITEMS].forEach(item => { ...):

async Demo1() {
  for(let item of [ARRAY OF ITEMS]) {
    await this.uploadItem(item);
  }
}

修改后的 Demo1 函数将如下所示:

async Demo1() {
  //Traversing around each fieldInfo
  for (let item of this.dataPresent.items) {
    if (item.model) {
      //Upload item model API Call
      await this.uploadItem(item.model)
      //PUT API Call
      let response = await this.putItemModel();
      var result = response.data;
      //Add itemModel fetched from API response
      models.push(result);
      console.log(result)
    } else {
      //Inside item price details
      console.log("inside item price");
      //API call for fetching price info
      this.getitemPriceInfo(item.id);
    }
  };
}

请注意,我还没有测试过这个,因为我没有完整的代码来插入它,所以我不能完全保证它会工作。如果没有,请告诉我,以便我帮助修复它

Here's该解决方案的一个糟糕的模型。

关于javascript - 在 for 循环 VueJS 中同步 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66681822/

相关文章:

javascript - Vue.js : How to use a computed property to modify string and apply dynamically as CSS class

javascript - 正则表达式在javascript中跨越-9.99到0的范围

javascript - IE11 : empty http request header not being passed

javascript - 正则表达式在行首匹配字符串分组

node.js - 在 VSTS 构建期间,使用 npm 脚本,如何确定触发构建的分支?

node.js - 请求在express.js中未定义

javascript - 如何使用 mongoose 填充嵌套在数组对象中的引用?

javascript - 检查 JSON 对象中的值

javascript - 过滤数组以产品 checkin 事件记录

javascript - Vue.js - 如何正确监视嵌套数据