【问题标题】:How to make sure the function is executed in VueJS如何确保函数在 VueJS 中执行
【发布时间】:2021-02-14 22:10:03
【问题描述】:

我正在尝试执行 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() 需要更多时间来处理数据。正如您在代码中看到的,我添加了加载标志。因此,fire 函数只会在所有函数都加载后执行。 我认为这不是最好的方法,所以我想听听您对此的看法。

你会怎么处理?

【问题讨论】:

    标签: javascript vue.js asynchronous async-await promise


    【解决方案1】:

    使用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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-21
      • 2018-04-14
      • 2021-04-05
      • 2014-12-11
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2021-07-13
      相关资源
      最近更新 更多