js中for循环里面有异步请求怎么解决?

        axios.post('/operationlog/list', moduleParams).then((res) => {
            if (res.status === 200) {
              this.moduleList = res.data.items;

              stepParams.append('category', "");
              stepParams.append('needPlayback', true);

              for (let i = 0; i < this.moduleList.length; i++) {
                stepParams.set('category', this.moduleList[i].category)
                axios.post('/operationlogitem/list', stepParams).then((res) => {
                  console.log(res.data.items);
                }).catch((e) => {
                  console.log(e);
                })
              }
            }
          }

代码如上,根据外层请求获取到多个不同的category,但是for循环是同步,里面的post请求是异步的,所以始终以最后一项的category为参数发送请求.请问如何修改代码按照每一项的category参数发送post请求,目前只知道用递归解决,有没有其他办法?

阅读 16.7k
5 个回答

可以用生成器函数或者async/await再用babel转

可以用async/await

其实是闭包问题,也可以使用async/await来解决

闭包问题,简单解决.

for (let i = 0; i < this.moduleList.length; i++) {
  (function(cur) {
      stepParams.set('category', this.moduleList[cur].category)
      axios.post('/operationlogitem/list', stepParams).then((res) => {
        console.log(res.data.items);
      }).catch((e) => {
        console.log(e);
      })
  })
}

但是let关键字应该就能避免这个问题了

参照:
https://www.cnblogs.com/CoderMonkie/p/js-async-in-loop.html


// 循环中调用异步
let arr = []
new Promise((res, rej) => {
    for (let index = 0; index < 5; index++) {
        new Promise((resolve, reject) => {
            resolve(index)
        })
        .then((i) => {
            arr.push(index)
        })
    }
    res()
}).then(() => {
    console.log(arr)
})


// -----

// async/await 版本 循环(forEach)中调用异步
async function processArray(array) {
    if(toString.call(array) != '[object Array]'){
        console.log(array)
        return
    }
    array.forEach(async (item) => {
        await processArray(item);
    })
    console.log('Done!');
}
processArray(['a', 'b', 'c'])

// 结果:像同步一样的预期结果
// a
// b
// c
// Done!
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进