Jim*_*Jim 12 javascript interface promise async-await typescript
我试图async/await在一个角度1.5.5项目中使用.
鉴于这种服务方法
getDocumentTypes(): angular.IPromise<DocumentType[]> {
var url = "api/document/types";
this.$log.log(url);
return this.$http.get(url).then(_ => _.data);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建async / await该方法的一个版本.
async getDocTypes(): angular.IPromise<DocumentType[]> {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}}
Run Code Online (Sandbox Code Playgroud)
Intellisense显示错误:
TS1055类型'angular.IPromise'不是有效的异步函数返回类型,ES5/ES3因为它不引用与Promise兼容的构造函数值.
有没有使用正确的方式角承诺在打字稿2.1与async/ await?
async/await 可以在 angularjs 1.5 中工作
如果$q调度程序被Promise替换Bluebird。
通过添加以下内容app.ts
export class Module {
app: ng.IModule;
constructor(name: string, modules: Array<string>) {
this.app = module(name, modules);
}
}
function trackDigests(app) {
app.run(["$rootScope",$rootScope => {
Promise.setScheduler(cb => {
$rootScope.$evalAsync(cb);
});
}]);
}
export var app: ng.IModule = new Module("app", []).app;
trackDigests(app);
Run Code Online (Sandbox Code Playgroud)
常规$q调度程序被换出。像这样的代码开箱即用!
async $onInit() {
this.start();
try {
var key = await this.powerService.getKey(this._apiKey.partyAccountNumber);
var sites = await this.powerService.loadSites(this._apiKey.partyAccountNumber);
await this.showSummary(sites);
this.stop(true);
} catch (error) {
this.$log.error(error);
this.stop(false);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以返回Promise或ng.IPromse从您的服务方法中返回,因为它们是可以互换的。
export interface IPowerService {
setKey(key: pa.PowerApi): ng.IPromise<dm.ClientSite[]>;
getKey(partyAccountNumber: string): Promise<pa.PowerApi>;
}
Run Code Online (Sandbox Code Playgroud)
通过在测试工具中使用上述内容trackDigests,单元测试也可以使用。async / await
在我的例子中,我添加了以下内容webpack.test.js,以便能够以与业力async/await测试相同的方式运行。
plugins: [
new webpack.ProvidePlugin({
Promise: 'bluebird'
})
],
Run Code Online (Sandbox Code Playgroud)