gpt4 book ai didi

javascript - 如何确保函数在 VueJS 中执行

转载 作者:行者123 更新时间:2023-11-30 14:22:49 26 4
gpt4 key购买 nike

我正在尝试执行 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;

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

dataForFirst, dataForSecond, undefined;

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

你会怎么处理?

最佳答案

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

关于javascript - 如何确保函数在 VueJS 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52462012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com