繁体   English   中英

TypeScript - 异步等待不等到功能完全执行?

[英]TypeScript - async await not wait until funtion fully executed?

从存储中获取用户名、密码和标题后,我需要从 API 中获取数据。 因此,在最终调用 API 之前,我使用了三次异步等待。

可以正确获取数据,但不知何故刷新超时 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);
        
      }

已尝试删除异步等待,并像这样放置代码,但仍未按预期工作。 似乎 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);

      }

在第一个示例中,您混合使用 await 和.then,最好使用一个或另一个。 这是用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM