javascript - 如何判断循环何时完成。使用 JavaScript、Vue 和 AXIOS

标签 javascript arrays vue.js axios

我有一个来自 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/

相关文章:

java - 为什么我在此素数检查中收到 ArrayIndexOutOfBoundsException?

php - 查找数字列表中的空白

vue.js - Nuxt.js npm run build 导致一些JS文件找不到

javascript - 从 Vuex 中的数组中删除特定项目

javascript - vue-cli3 eslint vue/script-indent 与编译器冲突

javascript - 浏览器卡在媒体查询上

PHP:创建某种公共(public)变量池,PHP 代码可以从中获取变量

javascript - YTPlayer 背景视频不自动播放

javascript - req.session.passport.user 未定义

循环时无法比较数组上的字符串