首页 > 解决方案 > 如何确保函数在 VueJS 中执行

问题描述

我正在尝试执行 3 个函数,然后在 console.log 之后它们更改的值。我认为应该有更好的方法来解决这类问题,但我不确定它是什么。我所做的是我去了老学校,并添加了加载标志。基本上,loading = 3当函数被加​​载时,loading--

我想演示一下我当前的代码(实际上它不一样,但它可以用于演示目的),所以你可以感受一下:

data:() => ({
  loading: 3,
  first: null,
  second: null,
  third: null
}),

methods: {
  first() {
    this.$route.get('/data/for/first').then(response => {
      this.first = response.data;
      this.loading--;
    })
  },
  second() {
    this.$route.get('/data/for/second').then(response => {
     this.second = response.data;
     this.loading--;
    })
  },
  third() {
    this.$route.get('/data/for/third/a').then(responseA => {
      let thirdA = responseA.data;
      this.$route.get('/data/for/third/b').then(responseB => {
        let thirdB = responseB.data;

        if (thirdA === thirdB) {
          this.third = true;
        }

        this.loading--;
      })
    })
  },
  fireFunctions() {
    this.first();
    this.second();
    this.third();
  }
},

watch: {
  loading: function() {
      if (this.loading === 0) {
          console.log(this.first, this.second, this.third)
      }
   }
}

输出如下所示:

dataForFirst, dataForSecond, dataForThird;

但是,如果我不使用观察者,并在 mount() 中加载 this.fireFunctions() 我得到:

dataForFirst, dataForSecond, undefined;

现在,据我了解,这种情况正在发生,因为 this.third() 需要更多时间来处理数据。正如您在代码中看到的,我添加了加载标志。因此,只有在加载所有函数时才会执行触发函数。我认为这不是最好的方法,所以我想听听您对此的看法。

你会怎么处理?

标签: javascriptvue.jsasynchronousasync-awaitpromise

解决方案


用于Promise.all等待所有异步函数返回,然后运行您需要的任何代码,例如:

methods: {
  async all() {
    let [first, second, third] = await Promise.all([
      this.$route.get('/data/for/first'),
      this.$route.get('/data/for/second'),
      this.$route.get('/data/for/third')
    ]);
    this.first = first;
    this.second = second;
    this.third = third;
    console.log(first, second, third);
  }
}

推荐阅读