Javascript 如何实现Typescript异步等待模式:承诺在哪里
我在学习角度和打字 我有一个CustomerService,在这个服务中我有一个方法,我希望从RESTfull服务返回一组客户 最初,我创建了GetCustomers函数,因此:Javascript 如何实现Typescript异步等待模式:承诺在哪里,javascript,angularjs,asynchronous,typescript1.7,Javascript,Angularjs,Asynchronous,Typescript1.7,我在学习角度和打字 我有一个CustomerService,在这个服务中我有一个方法,我希望从RESTfull服务返回一组客户 最初,我创建了GetCustomers函数,因此: public GetCustomers(): Dtos.ICustomer[] { var _customers: Dtos.ICustomer[]; this._httpService.get('http://localhost/myTestApi/api/customers/')
public GetCustomers(): Dtos.ICustomer[] {
var _customers: Dtos.ICustomer[];
this._httpService.get('http://localhost/myTestApi/api/customers/')
.success(function (data) {
_customers = data as Dtos.ICustomer[];
}).error(function (error) {
console.log(error);
});
return _customers;
}
这个函数最终会获得客户,但显然它会在httpservice实际获得数据之前返回客户
在这一点上,我认为我可以使用Typscript async/await,而这正是我陷入混乱的时候
我想这样写我的函数:
public async GetCustomers(): Dtos.ICustomer[] {
var _customers: Dtos.ICustomer[];
await this._httpService.get('http://localhost/myTestApi/api/customers/')
.success(function (data) {
_customers = data as Dtos.ICustomer[];
}).error(function (error) {
console.log(error);
});
return _customers;
}
我立即收到此错误:错误TS1055类型“Dtos.icCustomer[]”不是有效的异步函数返回类型
我找到了这个
但是,它使用了一个Promise对象:returnnewpromise
如果我试图重新编写GetCustomers方法签名,则:
public async GetCustomers(): Promise<Dtos.ICustomer[]> {}
public async GetCustomers():Promise{}
我得到一个错误:
找不到名称“Promise”
我需要导入一些东西才能获得承诺吗?我会再次查看角度为$q的承诺对象: $q 它处理你需要的承诺
public getCustomers(): ng.IPromise<Dtos.ICustomer[]> {
var lDefer: ng.IDeferred<Dtos.ICustomer[]> =
this.$q.defer<Dtos.ICustomer[]>();
this._httpService.get('http://localhost/myTestApi/api/customers/')
.then(( inResult: any ) => {
let lResultList: Dtos.ICustomer[] = inResult.data;
lDefer.resolve( lResultList );
},
( inError: any ) => {
lDefer.reject( inError );
});
return lDefer.promise;
}
注意-有一个打字文件可从以下网站获得:
您可以通过tsd(现已弃用)或
tsconfig.json
文件中编译器选项下的安装'q'类型脚本定义:
您需要添加:
“lib”:[“dom”、“dom.iterable”、“scripthost”
“es2015.promise”
,“es2015”]
我使用es2015目标,但lib也适用于其他目标。
在vscode中,您将拥有intellisense。可能是重复的是我看到了,但我的承诺不存在?Typescript似乎对Promise一无所知。如果我将我的方法签名更改为public async GetCustomers():Promise{…},我会收到一个错误,声明“找不到名称‘Promise’)这肯定会使您的问题与链接的问题有所不同,请编辑它以包含此信息。是的,我意识到这一点,并对其进行了适当编辑。Promise在lib.es6.d.ts中声明。您是否已在tsconfig.json中将编译选项.target设置为“es6”?
import IPromise = angular.IPromise;
import IDeferred = angular.IDeferred;
static $inject = ['$q', ...];
constructor( protected $q:angular.IQService, ... ) {
super( $q );
}