我有一个来自 Syncfusion 的数据网格,并且有一列复选框。当我按下按钮时,代码读取所有选定的行,创建一个数组并循环,直到该过程结束。
this.selectedRecords = this.$refs.grid.ej2Instances.getSelectedRecords();
this.selectedRecords.forEach(function(arg, index) {
call HTTP API request. with AXIOS
get the return values and store it to the database
}
我可以选择 100 多行,并且我需要能够判断所有 API 调用何时完成。
我已经放慢了通话速度,因此每秒最多只能进行 10 次通话
axios.interceptors.request.use(
function(config) {
setTimeout(console.log("here request interceptor"), 100);
return config;
},
function(error) {
return Promise.reject(error);
}
);
我已经尝试过
if (self.selectedRecords.length - 1 === index) {
alert("Done");
}
但由于不能保证按顺序处理行,因此可能过早调用“完成”。
我希望我已经给了你足够的代码来理解我的问题,但又没有给你太多的代码,以免让它变得草率。
最佳答案
如果我理解正确,那么您应该只需要收集数组中的 promise ,然后使用 Promise.all
等待它们全部完成:
var requests = this.selectedRecords.map(function(arg, index) {
return axios.get(/* request details here */);
});
Promise.all(requests).then(function() {
console.log('Done')
});
如果您需要使用 then
处理各个请求,也可以,只需将其链接到 axios.get
调用的末尾即可:
return axios.get(/* request details here */)
.then(function(response) {
// Handle response
})
更新:
请求拦截器可以返回 promise ,如果您想阻止请求的执行,这是必要的:
http.interceptors.request.use(function (config) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(config)
}, 5000)
})
})
请注意,上面的示例没有执行适当的限制,它只是延迟请求。它纯粹是为了说明如何将 Promise 与拦截器一起使用。您没有在问题中包含真正的拦截器,因此我无法更具体。
关于javascript - 如何判断循环何时完成。使用 JavaScript、Vue 和 AXIOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57775390/