12

I am attempting to use async/await in an angular 1.5.5 project.

Given this service method

    getDocumentTypes(): angular.IPromise<DocumentType[]> {
        var url = "api/document/types";
        this.$log.log(url);
        return this.$http.get(url).then(_ => _.data);
    }

I am attempting to create an async / await version of the method.

    async getDocTypes(): angular.IPromise<DocumentType[]> {
                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    }}

Intellisense shows an error: TS1055 Type 'angular.IPromise' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.

Is there a correct way to use an angular promise in typescript 2.1 with async / await?

Jim
  • 14,952
  • 15
  • 80
  • 167
  • where are the type annotations for angular coming from? could that be updated? – Daniel A. White Dec 15 '16 at 14:44
  • updating the typings has proved to be a problem as well. http://stackoverflow.com/questions/41216046/updating-angular-1-5-10-typings-global-vs-external-module – Jim Dec 20 '16 at 06:17
  • I have successfully updated the typings using `npm i @types/angular`. There is an interface in the 2.1 lib.d.ts called `PromiseLike` but it's not clear how it might be used. – Jim Dec 22 '16 at 04:47

3 Answers3

2

You may need to just use Promise directly:

async getDocTypes(): Promise<DocumentType[]> {

}}

The typescript 2+ generated code, will fall outside of the angular digest cycle, and the component / directive will not update the view / model correctly.

Jim
  • 14,952
  • 15
  • 80
  • 167
NYCdotNet
  • 4,500
  • 1
  • 25
  • 27
  • `Promise` is not defined. – Jim Dec 22 '16 at 04:48
  • Is that a TypeScript error or runtime error? If TypeScript, you may need to add `"es2015.promise"` to your `compilerOptions` / `lib` setting in tsconfig.json. – NYCdotNet Dec 22 '16 at 14:25
  • this did not seem to work when I originally attempted it, with webpack.js, and ts-loader, and it seems to work with `Promise` – Jim May 02 '17 at 12:08
1

async / await can work in angularjs 1.5

if the $q scheduler is swapped out with Bluebird promises.
By adding the following to 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);

The regular $q scheduler is swapped out. Code like this works out of the box!

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);
    }
}

You can return Promise or ng.IPromse from your service methods, as they are interchangable.

export interface IPowerService {
    setKey(key: pa.PowerApi): ng.IPromise<dm.ClientSite[]>;
    getKey(partyAccountNumber: string): Promise<pa.PowerApi>;
}

By using the above trackDigests in the test harness, unit tests will also work with async / await In my case, I added the following to my webpack.test.js to enable async/await to function the same way with karma tests.

plugins: [
    new webpack.ProvidePlugin({
        Promise: 'bluebird'
    })
],
Jim
  • 14,952
  • 15
  • 80
  • 167
1

disclaimer: this answer works in 2018 with TS 3.2.2. I am not sure they are similar in 2.1.

currently there are compiler options allowing libraries to be added to the compilation. To use async/await you have the next options:

  • command line: --target ES6 --lib es2015.generator.
  • Config file:
    
    {
        "compilerOptions": {
            "target": "es5",
            "lib": ["es2015.generator"]
            ...
       }
       ...
    }
    
Kanekotic
  • 2,824
  • 3
  • 21
  • 35