Javascript 异步/等待语法有时似乎不起作用
我正在使用Vue,希望使用async/await为我的函数a和B提供一个序列Javascript 异步/等待语法有时似乎不起作用,javascript,vue.js,Javascript,Vue.js,我正在使用Vue,希望使用async/await为我的函数a和B提供一个序列 result is false by default mounted() { this.A(); this.B(); } async A() { this.result = await this.$api... } async B() { if(this.result) let data = await this.$another1 api... else let data = awa
result is false by default
mounted() {
this.A();
this.B();
}
async A() {
this.result = await this.$api...
}
async B() {
if(this.result) let data = await this.$another1 api...
else let data = await this.$another2 api...
}
我假设在函数A调用api并返回'result'值之后,函数B完成他的工作
然而,有时函数B中的api在“this.result”之前调用了“another2 api”,即使函数A从$api接收到值后的结果为“true”,也会获取其值
我希望这是正常的行为
这是我刷新页面时有时会发现的错误
如何解决此问题?
A
返回承诺。如果mounted()
函数不是能够使用wait
的异步函数,则必须使用then
this.A().then(()=>{
this.B();
});
(抱歉,上面是typescript。您可以找出如何使用javascript…这根本不是我的专长。)您需要告诉挂载的方法在调用第二个方法之前等待第一个方法。记住用
async
假装挂载()
async mounted() {
await this.A();
this.B();
}
async mounted() {
await this.A();
await this.B();
}
您需要将
装入
作为异步
async mounted() {
await this.A();
this.B();
}
async mounted() {
await this.A();
await this.B();
}
异步函数返回一个可以等待的承诺,或者在第一个函数完成后使用
.then()
执行第二个函数。您的TypeScript代码片段在JavaScript中是相同的。这个东西是我在JavaScript中经常遇到的问题