简体   繁体   English

如果在调用它的地方有等待,我是否应该对方法进行异步/等待?

[英]Should I have and async/await on a method if there is an await at the point where it is called?

I have these two Typescript methods:我有这两种打字稿方法:

async getCertURL(pol: string): Promise<string> {
  return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then(
    (response) => {
      return response.data.certURL;
    })
    .catch((err) => 
      this.loggingService.logError('Error generating reissue cert forward URL ' + err));
}

async getCert(pol: string): Promise<string> {
return Api.getData(await this.getCertURL(policy), {timeout: 60000}).then(
  (response) => {
    return response.data;
  })
.catch((err) => 
  this.loggingService.logError('Error cert not reissued ' + err));
}

I thought if I had an await before await this.getCertURL(policy) in my getCert() I would not require one at Api.getData() in getCertURL but getCert() throws an exception without it.我想如果在我的getCert()中的 await this.getCertURL await this.getCertURL(policy)之前有一个await ,我将不需要在Api.getData() getCertURL getCert()在没有它的情况下抛出异常。

Am I correct to include it or is there some other way I should be doing this?我是否正确包含它,或者我应该以其他方式这样做吗?

You need to use await if the value on the right hand side is a promise and you want the resolved value returned instead of the promise.如果右侧的值是一个承诺,并且您希望返回已解决的值而不是承诺,则需要使用await

Since getCertURL is marked as async , it will return a promise.由于getCertURL被标记为async ,它将返回一个承诺。

You need the value, so you need await .你需要这个值,所以你需要await


On the other hand, since (inside getCertURL ) you do nothing with value of the promise returned by Api.getData().then().catch() except return it (causing it to be wrapped in a promise) you could omit the await and async from that function.另一方面,由于(在getCertURL内部)你对Api.getData().then().catch()返回的承诺值什么都不做,除了返回它(导致它被包装在一个承诺中)你可以省略从该函数awaitasync You'd have clearer code if you replaced the then() and catch() with await and try {} catch {} though).如果您将then()catch()替换为awaittry {} catch {} ,您将拥有更清晰的代码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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