【发布时间】:2021-06-15 07:21:40
【问题描述】:
我正在尝试在 for loop which each loop having to call a API 中获取同步流。
流程总结如下:
- 包含 forloop 的
Demo1() function会一个接一个地执行,但在每个循环中它都会执行一次 API 调用。 -
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 先执行,然后从 MainFunction 启动 processFinalAPICall()?
如果我的做法正确,请告诉我。谢谢:)
由于我们的项目依赖关系,我正在使用 Node 版本 8.11。
已编辑: 添加 API 函数调用以供参考
【问题讨论】:
标签: javascript node.js vue.js asynchronous async-await