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

时间:2015-12-12 20:05:39

标签: javascript angularjs asynchronous typescript1.7

我学习角度和打字稿。

我在此服务中有一个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.Customer []'不是有效的异步函数返回类型。

我发现了Async/Await , simple example (typescript)

然而它使用Promise对象:返回新的Promise

如果我尝试重写我的GetCustomers方法签名:

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

我得到并且错误:

找不到姓名&#39;承诺&#39;

我是否需要导入一些内容才能获得承诺?

2 个答案:

答案 0 :(得分:2)

我会建议看一下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 );
}

P.S。 - Definitely Typed提供了一个打字文件:http://definitelytyped.org/

您可以安装&#39; q&#39;通过 tsd (现已弃用)或typings

定义打字稿

答案 1 :(得分:0)

tsconfig.json文件的compilerOptions下:

你需要添加:

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

我使用es2015目标,但lib也适用于其他目标。 在vscode中,你将有智能感知。