在循环数组中每一项都要使用异步请求时,使用for of

问题

循环遍历一个数组,每个数据项都需要调用接口请求数据(异步),如果用forEach 和 map 等数组方法去遍历,异步的函数是不会等待的,加了await也没有作用(下面的循环了5次)

  methods: {
    async getList2() {
      //异步请求数据
      await getStaff(this.queryParams).then((response) => {
        console.log("222222----");
      });
    },
    async printAllPDF() {
      staffList.forEach(async (item) => {
        console.log("111111----");
        //调用异步的函数
        await this.getList2();
      });
      console.log("333333----");
    },
  },

我希望得到的应该是 输出一个“111111----”,再输出一个“222222----”,循环5次后最后输出“333333----”,但是实际的情况如下:

输出了5次“111111----”,又输出了“333333----”。因为执行异步函数this.getList2();并没有等它执行完,5个异步后面执行,所以出错,使用的数据也会出现错乱

因为数组的方法(forEach, map, filter 等)通常是同步执行的,而且,就算我使用Promise.all 来等待每一个异步执行完再执行后面的语句

  methods: {
    async getList2() {
      //异步请求数据
      await getStaff(this.queryParams).then((response) => {
        console.log("222222----");
      });
    },
    async printAllPDF() {
      let promises = []
      staffList.forEach(async (item) => {
        console.log("111111----");
        //调用异步的函数
        const ceshiItem = await this.getList2();
          promises.push(ceshiItem)
      });

      await Promise.all(promises)
      console.log("333333----");
    },
  },

也是无济于事,输出还是一样的结果

解决方法

使用for of 遍历

  methods: {
    async getList2() {
      //异步请求数据
      await getStaff(this.queryParams).then((response) => {
        console.log("222222----");
      });
    },
    async printAllPDF() {
      for(const item of staffList){
        console.log("111111----");
        //调用异步的函数
        await this.getList2();
      }
      console.log("333333----");
    },
  },

正确输出:

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值