VUE的一个函数执行完毕之后立即执行另一个函数__Vue.js
发布于 3 年前 作者 banyungong 2483 次浏览 来自 分享
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利

主题列表:juejin, github, smartblue, cyanosis, channing-cyan, fancy, hydrogen, condensed-night-purple, greenwillow, v-green, vue-pro, healer-readable, mk-cute, jzman, geek-black, awesome-green

贡献主题:https://github.com/xitu/juejin-markdown-themes

theme: cyanosis highlight:

使用场景:A函数向后台请求得到数据dataA,B函数需要利用到数据dataA立即进行一些计算或者向后台请求别的数据, 这时候写

this.A();
this.B();

会报错,因为异步的原因,执行B的时候A的数据还没返回。

方法

首先执行的函数A:

A() {
      const params = {
        projectName: this.listSearchKey
      };
      // 利用promise
      return new Promise((resolve, reject) => {
        // 异步请求
        projectList(params)
          .then(res => {
            if (res.code === '0') {
              this.dataA = res.data;
              // 返回想要的数据
              resolve(this.dataA);
            }
          })
          .catch(err => {
            console.error(err);
          });
      });
}

接着执行的函数B

B(id) {
    //用到了函数A的返回数据dataA,并且希望拿到返回数据之后立即执行
      const params = {
        projectId: id || this.dataA[0].projectId
      };
      taskList(params)
        .then(res => {
          if (res.code === '0') {
            this.tableData = res.data.list;
            this.total = res.data.total;
          }
        })
        .catch(err => {
          console.error(err);
        });
    },

在执行时这样写

this.getProjectList().then(val => {
      this.getTaskList();
    });

版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者: 到了冬天以后 原文链接:https://juejin.im/post/6914096805437243406

回到顶部