我试图查看在返回Promise时是否在.then()中返回空块是正确的模式。
下面是方法以及如何在.then()中返回代码。这段代码有效,但是想知道更好的方法。即使是tslint也在对此进行编译。
private async somexMethod(id: string, params?: someParams): Promise<void> {
const url: string = "http://someendpointUri";
const headers = await getMyHeadersAsync(id);
// Here calling my API that returns the promise
return this._myHttpClient.delete(url, { headers, params: someParams })
.pipe(retryWhen(HttpUtil.someXPolicyForRetry))
.toPromise() // this converts Observable<ResponseXyz> to Promise<ResponseXyz>
// tslint:disable-next-line: no-empty
.then(() => { }) // Is this the correct way to return for Promise<void> or .then(() => null) ?
.catch(() => {
// log error msg
});
}
这里的Observable由delete方法以及此函数HttpUtil.someXPolicyForRetry返回。使用toPromise()转换为Promise后,如何返回Promise?
上面用空块调用.then()是使用的正确模式还是还有其他更好的方法?我也看到.then(()=> null)作为另一个选项,但是不确定我们是否还有其他更好的方法返回Promise。
请注意,我想在codesnippet方法中保持相同的模式,例如返回this._myHttpClient.delete(..),并且我不想将其更改为其他返回新Promise(resolve,拒绝)或调用resolve()的模式。
即使您没有明确返回承诺,异步函数也始终会返回承诺。
然后在代码中,只要您不返回任何内容,就总是希望 Promise<void>
private async somexMethod(id: string, params?: someParams): Promise<void> {
const url: string = "http://someendpointUri";
const headers = await getMyHeadersAsync(id);
this._myHttpClient.delete(url, { headers, params: someParams }) // removed the return
.pipe(retryWhen(HttpUtil.someXPolicyForRetry))
.toPromise() // this converts Observable<ResponseXyz> to Promise<ResponseXyz>
//.then(() => { }) // no need for this
.catch(() => {
// log error msg
});
}
这是4分钟的有关异步等待的内容:https : //medium.com/better-programming/should-i-use-promises-or-async-await-126ab5c98789
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句