【问题标题】:Passthrough Promises, does the function need to be async?Passthrough Promises,函数需要异步吗?
【发布时间】:2021-07-23 14:46:53
【问题描述】:

问题是:是否需要将只是传递函数的 javascript 函数标记为异步。 这是标记为 async with a await 的原始代码。 Sonar 将 await 标记为多余。所以我删除了等待,但我的问题是这个函数是否需要被标记为异步,因为它没有做任何异步操作。它现在是一个简单的传递函数。

private async getResponse(url: string): Promise<HttpResponse> {
    const axiosConfig = new AxiosRequestConfig();
    axiosConfig.method = HttpMethod.Get;
    const response = new HttpResponse(url, axiosConfig);
    return await response.sendRequest(new HttpRequestOptions(null));
}

这是我更新的内容,但不确定它是否正确。运行测试时代码不会出错。

private getResponse(url: string, options: HttpRequestOptions): Promise<HttpResponse> {
    const httpSettings = this.getHttpSettings(options);
    const fullUrl = this.isAbsolutUrl(url) ? url : `${httpSettings.getBaseAddress()}${url}`;
    const axiosConfig = new AxiosRequestConfig(httpSettings);
    const response = new HttpResponse(fullUrl, axiosConfig);
    return response.sendRequest(options);
 }

这是被调用的 sendRequest,它返回一个承诺并被标记为异步,所以我认为它涵盖了调用方法被标记为异步。

export class HttpResponse { 
  public async sendRequest(options: HttpRequestOptions): Promise<HttpResponse> {
    try {
      switch (options.method) {
        case HttpMethod.Post:
          this._response = await axios.post(this.url, options.body, this.config);
          break;

        case HttpMethod.Get:
          this._response = await axios.get(this.url, this.config);
          break;

        default:
          break;
      }
      this._statusCode = this.response.status;
      this._headers = this.response.headers;
    } catch (error) {
      this.logger.error(error);
      this._error = error;
    }
    return this;
  }
}

谢谢

【问题讨论】:

  • 唯一的区别是您调用的任何方法和构造函数是否抛出异常(同步)。如果他们从不这样做,这两个 sn-ps 是绝对等价的,我会避免不必要的 async

标签: javascript asynchronous promise


【解决方案1】:

如果你在函数内部使用await,你只需要将函数标记为async

使用await 获取立即返回的值是没有意义的。

所以看看你原来的功能:

private async getResponse(url: string): Promise<HttpResponse> {
    const axiosConfig = new AxiosRequestConfig();
    axiosConfig.method = HttpMethod.Get;
    const response = new HttpResponse(url, axiosConfig);
    return await response.sendRequest(new HttpRequestOptions(null));
}

你有return await ... 所以await 是没有意义的。

如果您删除了您根本没有使用await,那么使用async 毫无意义。

【讨论】:

  • return await 毫无意义的一个警告是,如果它在try 块中,那并不是毫无意义的;它确保try 块的关联catch(如果有)在等待的承诺拒绝时被触发,并且它的finally(如果有)在承诺解决之前不会运行。但是在函数的顶层(或者在try 之外),它确实是没有意义的。 :-)
猜你喜欢
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 2016-06-17
  • 2018-12-16
  • 1970-01-01
  • 2023-01-22
  • 2016-05-20
  • 2017-12-16
相关资源
最近更新 更多