javascript - 如何确保函数在 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() 需要更多时间来处理数据。正如您在代码中看到的,我添加了加载标志。因此,只有在加载所有函数时才会执行触发函数。我认为这不是最好的方法,所以我想听听您对此的看法。
你会怎么处理?
解决方案
用于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 - (MongoDB) Data submitted from user A is being sent into User B's document
- javascript - Can I use a
7
(number in a paragraph) as a value in JavaScript? - android - Triggering Skype call via Android app - 'Start Call' pop-up doesn't go away when call starts
- spring - Spring 5 with Spring-social reports java.lang.NoSuchMethodError: org.springframework.web.util.WebUtils.extractFullFilenameFromUrlPath
- docker - How do I test my Fluentd config in combination with Elasticsearch?
- java - ArrayBlockingQueue+synchronized in java
- reactjs - react-native(或仅反应)的非线性向导组件
- django - 如何将 django 连接到 kubernetes 中的 postgres?
- java - 识别 Java 字符串字符的小写或大写
- parallel-processing - 当测试作业从 fastlane fastfile 运行时,如何在 Circle CI 中实现并行性?