我是靠谱客的博主 幸福大门,最近开发中收集的这篇文章主要介绍for循环中调用接口 async await Promise前言1.for循环2.异步接口总结,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

文章目录

  • 前言
  • 1.for循环
  • 2.异步接口
  • 总结


前言

for循环中 循环调用接口 然后等循环结束获取全部数据。


1.for循环

代码如下(示例):

async initMapInfoWindowChart(data) {
      const { data: res, code: code } = await getData({
        id: data.id,
      })
      if (code == 200) {
        if (res) {
          var chartList = []
          chartList = res
          for (let i in chartList) {
          //此处的resData  即为每次循环执行后 异步接口返回值
            let resData = await this.getHistoryList(i, chartList[i].id)
          }
          this.chartList = chartList
        }
      } else {
        this.$notify({
          type: 'error',
          title: '失败!',
          message: res.msg,
          position: 'bottom-right'
        })
      }
    },

2.异步接口

代码如下(示例):

async getHistoryList(i, id) {
      return new Promise(async resolve => {
        pageHistoryList({
          id: id
        }).then(res => {
          if (res.code == 200) {
            if (res.data) {
              var historyList = res.data
              resolve(historyList)
            }
          } else {
            this.$notify({
              type: 'error',
              title: '失败!',
              message: res.msg,
              position: 'bottom-right'
            })
          }
        })
      })
    },

总结

使用async await Promise化异步为同步 便于拼接数据

最后

以上就是幸福大门为你收集整理的for循环中调用接口 async await Promise前言1.for循环2.异步接口总结的全部内容,希望文章能够帮你解决for循环中调用接口 async await Promise前言1.for循环2.异步接口总结所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部