[vue]promise.all 等待所有请求完毕以后执行操作 两个异步接口按照顺序执行

原写法:
异步,分别调用接口,然后请求,多次请求影响性能
api接口文件

export function getInnerCourseList(params) {
    
    
  // 分页信息params
  return request({
    
    
    url: '/course/sys/v1/course/nopagelist',
    method: 'get',
    params,
  })
}
// 3.查询社团详情列表  跳转类型:社团详情-适用社团列表
// https://dev-careeradmin.wanxue.cn/career/sys/v1/association/likelist
export function getAssociationList(params) {
    
    
  // 分页信息params
  return request({
    
    
    url: '/career/sys/v1/association/likelist',
    method: 'get',
    params,
  })
}
import {
    
    
    getInnerCourseList,
    getAssociationList,
  } from '@/api/marketing/activityBounced'
methods:{
    
    
    async getCourseList() {
    
    
      	const r = await getInnerCourseList()
      	this.courseOptions = r.result
	},
	async getAssocialList() {
    
    
  		const r = await getAssociationList()
  		this.associationOptions = r.result
	},
}
mounted() {
    
    
  // 关联2 内部跳转-适合课程列表
  this.getCourseList()
  // 关联3-社团详情-适用社团列表
  this.getAssocialList()
}

现在使用promise

<script>
  import {
    
    
    getInnerCourseList,
    getAssociationList,
    addOneActivityBounced,
    editOneActivityBounced,
    uploadOneActivityImg,
  } from '@/api/marketing/activityBounced'
  import {
    
     ElMessage } from 'element-plus'
  export default {
    
    
    name: 'TableEdit',
    emits: ['fetchData'],
    data() {
    
    
      return {
    
    
        courseOptions: [], //关联2-课程列表
        associationOptions: [], //关联3-社团详情
      }
    },
    mounted() {
    
    
      // 关联2 内部跳转-适合课程列表
      this.getCourseList()
      // 关联3-社团详情-适用社团列表
      this.getAssocialList()
      Promise.all([this.getCourseList(), this.getAssocialList()])
        .then((res) => {
    
    
          // console.log('res:', res)
          this.courseOptions = res[0].result
          this.associationOptions = res[1].result
        .catch((err) => {
    
    
          console.log('err:', err)
        })
    },
    methods: {
    
    
      async getCourseList() {
    
    
        return new Promise((resolve) => {
    
    
          resolve(getInnerCourseList())
        })
      },
      async getAssocialList() {
    
    
        return new Promise((resolve) => {
    
    
          resolve(getAssociationList())
        })
      },
    },
  }
</script>

获取数据格式
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

注意:使用Promise之前要new
不然会报错,报错信息:

undefined is not a promise

每一个环节都要new

 new Promise((resolve,reject) => {
    
    
    req.on('end',() => {
    
    
        str = JSON.parse(str)
        resolve(str)
    })
}).then(str => {
    
     
    console.log(str)
    return new Promise(resolve => {
    
    
}

おすすめ

転載: blog.csdn.net/weixin_41056807/article/details/115729462