我想将promise链重构为async/await,但Typescript正在抱怨打字。为什么Typescript认为async/await返回承诺中包含的值?
TS2322:类型 'IHttpPromiseCallbackArg < IResp>' 是不能分配给键入 'IResp' ......
我想await
将返回常规值,而不是一个承诺。我错了吗?如果是这样,我如何分配一个键入以便编译所需的代码?
我以为await会返回与.then回调中第一个参数相同的值。我错了吗?
旧代码:
handleSubmit(form) {
const params = this.getParams(form);
this.myAsyncRequest(params)
.then((resp:IResp) => this.processResp(resp))
.catch((e:IServerError) => this.handleError(e));
}
所需的新代码:
async handleSubmit(form) {
const params = this.getParams(form);
try {
const resp:IResp = await this.myAsyncRequest(params); //typing error with "const resp:IResp"
this.processResp(resp);
} catch (e:IServerError) {
this.handleError(e);
}
}
如果我删除myAsyncRequest
返回类型所需的代码仍然打破;我认为Typescript直接从AngularJS库中推断出来。
myAsyncRequest(params:IParams):IHttpPromise<IResp> {
return $http.post('blah', data);
}
如果我从常量RESP声明中删除 “IResp”,processResponse抱怨IHttp < IResp>不等于IResp ...
processResp(resp:IResp) {
//do stuff
}
请提供一个最小的完整示例。 – NineBerry
IHttpPromiseCallbackArg类型不是承诺。这已经是函数调用的实际结果。请参阅http://definitelytyped.org/docs/angular-translate--angular-translate/interfaces/ng.ihttppromisecallbackarg.html – NineBerry
我可以将我的问题改写为 - “我认为await会返回与第一个参数相同的值在'.then'回调中,我错了吗?“ – user2954463