[英]TypeScript - async await not wait until funtion fully executed?
I need to fetch data from the API after getting the username, password and title from storage.从存储中获取用户名、密码和标题后,我需要从 API 中获取数据。 Hence I use async await thrice before finally calling the API.
因此,在最终调用 API 之前,我使用了三次异步等待。
The data can be fetched correctly, but somehow the refresh timeout function completed first before the getData function fully executed.可以正确获取数据,但不知何故刷新超时 function 在 getData function 完全执行之前首先完成。
doRefresh(event) {
setTimeout(async () => {
await this.storage.get('username').then(async username => {
await this.storage.get('password').then(async password => {
await this.storage.get('title').then(async tempName => {
await this.myService.getJSON(username, password, tempName, "keywordA", this.section).then(async ()=> {
await this.myService.getJSON(username, password, tempName, "keywordB", "trainingInfo"); }).finally(async ()=> {
await this.getData();
console.log('done');
event.target.complete();
});
})
})
});
}, 2500);
}
Have tried to remove async await, and put the code like this, but still not working as expected.已尝试删除异步等待,并像这样放置代码,但仍未按预期工作。 Seems like console.log / event.target.complete always execute first before waiting getData function complete.
似乎 console.log / event.target.complete 总是在等待 getData function 完成之前先执行。
doRefresh(event) {
setTimeout(() => {
this.storage.get('username').then(username => {
this.storage.get('password').then(password => {
this.storage.get('title').then(tempName => {
this.myService.getJSON(username, password, tempName, "keywordA", this.section).then(()=> {
this.myService.getJSON(username, password, tempName, "keywordB", "trainingInfo"); }).finally(()=> {
this.getData();
console.log('done');
});
})
})
});
event.target.complete();
}, 2500);
}
In the first example, you're mixing await and.then, best to use one or the other.在第一个示例中,您混合使用 await 和.then,最好使用一个或另一个。 Here's it re-written with async/await, it's much more readable in my opinion.
这是用 async/await 重写的,在我看来它更具可读性。
async () => {
try {
const username = await this.storage.get('username')
const password = await this.storage.get('password')
const tempName = await this.storage.get('title')
await this.myService.getJSON(username, password, tempName, "keywordA", this.section)
await this.myService.getJSON(username, password, tempName, "keywordB", "trainingInfo")
await this.getData();
console.log('done');
event.target.complete();
} catch (e) {
console.log("something went wrong")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.