vue中不同组件请求先后执行的问题

问题描述

M]E{1ZKA%P3FH47{I[5W14U.png

  这是vue下的一个组件 cofig下的index引用了details  details又引用了history和item 由于异步处理  
  导致进入某个页面时这个组件(包括子组件)会同时请求数据,这样导致后台出现问题,需求是当cofig下的
  index执行完请求操作,item再执行,执行完后history再执行

问题出现的环境背景及自己尝试过哪些方法

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)
cofig下需执行的方法

     async loadData() {
    let resp = await this.dispatch(ApplicationConfigGroupController.findByCriteria, {
      appInstGrpId: this.appInstGrp.id,
    })
    if (!resp.error) {
    ...
    }
  },

item下的方法

        async search() {
    let resp = await this.dispatch(ApplicationConfigGroupController.findItems, {
      applicationConfigGroupId: this.appInstGrp.id,
    })
    if (!resp.error) {
   ...
      }
    }
  },

hitory下的方法

    async search() {
  let resp = await this.dispatch(ApplicationConfigGroupController.getReleasesHistories, {
    applicationConfigGroupId: this.appInstGrp.id,
    ...this.query,
  })
  if (!resp.error) {
   
  }
},

你期待的结果是什么?实际看到的错误信息又是什么?

我希望先执行loaddata,然后执行item下的search,然后执行history下的search
阅读 2.7k
1 个回答

其实就是当前资源依赖于其他资源的加载嘛

/**
 * 不关心参数的函数类型
 * @typeparam R 函数的返回值类型
 */
export type ReturnFunc<R> = (...args: any[]) => R
/**
 * 等待指定的时间/等待指定表达式成立
 * 如果未指定等待条件则立刻执行
 * 注: 此实现在 nodejs 10- 会存在宏任务与微任务的问题,切记 async-await 本质上还是 Promise 的语法糖,实际上并非真正的同步函数!!!即便在浏览器,也不要依赖于这种特性。
 * @param param 等待时间/等待条件
 * @returns Promise 对象
 */
export function wait(param?: number | ReturnFunc<boolean>): Promise<void> {
  return new Promise(resolve => {
    if (typeof param === 'number') {
      setTimeout(resolve, param)
    } else if (typeof param === 'function') {
      const timer = setInterval(() => {
        if (param()) {
          clearInterval(timer)
          resolve()
        }
      }, 100)
    } else {
      resolve()
    }
  })
}

// 一个全局变量的位置,可能是 redux/vuex 之类的
const obj = {
  a: null,
  b: null,
  c: null,
}
async function a() {
  obj.a = 'a'
  console.log(obj.a)
}

async function b() {
  // 依赖于 a 函数执行完
  await wait(() => obj.a !== null)
  obj.b = 'b'
  console.log(obj.b)
}

async function c() {
  // 依赖于 b 函数执行完
  await wait(() => obj.b !== null)
  obj.c = 'c'
  console.log(obj.c)
}

Promise.all([a(), b(), c()])
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题