如何实现Typescript异步等待模式:Promise在哪里



我正在学习angular和Typescript。

我有一个CustomerService,在这个服务中,我有一种方法,我希望从RESTfull服务返回一组客户。

最初,我创建了GetCustomers函数,因此:

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真正得到数据之前返回_customers。

在这一点上,我认为我可以使用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.ICustomer[]"不是有效的异步函数返回类型。

我发现了这个Async/Await,简单的例子(typescript)

但是它使用了Promise对象:返回新的Promise

如果我试图重写我的GetCustomers方法签名,则为:

public async GetCustomers(): Promise<Dtos.ICustomer[]> {}

我得到错误:

找不到名称"Promise"

我需要进口一些东西才能获得Promise吗?

我建议查看Angular$q Promise对象:https://docs.angularjs.org/api/ng/service/$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;
    }

确保在控制器中注入$q对象:

import IPromise = angular.IPromise;
import IDeferred = angular.IDeferred;
static $inject = ['$q', ...];
constructor( protected $q:angular.IQService, ... ) {
    super( $q );
}

附言-有一个打字文件可从明确打字:http://definitelytyped.org/

您可以通过tsd(现已弃用)或打字

安装'q'Typescript定义

tsconfig.json文件中的compilerOptions:下

您需要添加:

"lib": ["dom", "dom.iterable", "scripthost","es2015.promise", "es2015"]

我使用es2015目标,但lib也适用于其他目标。在vscode中,您将拥有intellisense。

最新更新