【发布时间】: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