35

I am quite familiar with the async/await of C# and been using TypeScript for a year or so, can anyone please give a simple example explaining how it works in TypeScript?

It would be very helpful if the example includes Angular/jQuery promise, as it will give a clear view of a practical implementation.

Pranay Dutta
  • 2,483
  • 2
  • 30
  • 42
  • See Proposal: Async Functions on TypeScript https://github.com/Microsoft/TypeScript/issues/1664. Also https://smellegantcode.wordpress.com/2015/02/01/typescript-1-5-async-functions/ and http://www.dotnetcurry.com/javascript/1131/ecmascript6-async-using-generators-promises – Matija Grcic Sep 04 '15 at 15:41
  • 2
    The roadmap shows async/await as 2.0: https://github.com/Microsoft/TypeScript/wiki/Roadmap (as of [July 23rd](https://github.com/Microsoft/TypeScript/wiki/Roadmap/aa5e66fabe0d50ef53e6b05b3d1906a3eb40a35b)) – Jon Skeet Sep 04 '15 at 15:42
  • MatijaGrcic and @JonSkeet skeet ,thanks for the comments, i had already seen these documents but, really looking forward for some simple practical example ,so that i can integrate it with angularjs promise's – Pranay Dutta Sep 04 '15 at 15:45
  • So if you know it's not in 1.6, why did you tag your question 1.6? I would wait until the feature is available (e.g. in a 2.0 beta) - I'm sure there'll be plenty of examples then. – Jon Skeet Sep 04 '15 at 15:46
  • @JonSkeet it is ,as an experimental feature of 1.6 https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#typescript-16 – Pranay Dutta Sep 04 '15 at 15:48
  • 1
    @JonSkeet it's experimental in 1.6 with the `--experimentalAsyncFunctions` compiler option (and 1.6 beta was just released on wednesday) – David Sherret Sep 04 '15 at 15:48
  • @DavidSherret: Makes sense. – Jon Skeet Sep 04 '15 at 15:49
  • @PranayDutta: So there's an example in that documentation - it's not clear what you're looking for beyond that. (And of course things can change before it becomes non-experimental...) – Jon Skeet Sep 04 '15 at 15:49
  • @JonSkeet, just looking for some pratical example,because i was looking for this feature for many days ,now its there i want to implement it asap ,but need some pratical example (eg: using angular/jquery promise) – Pranay Dutta Sep 04 '15 at 15:51
  • now, that 1.7 is released and contains this feature, I changed the tag to 1.7 – Andrei Rînea Dec 11 '15 at 11:47

2 Answers2

35

The key is to use an ES6 Promise or something that implements the PromiseLike and PromiseConstructorLike interfaces found in lib.d.ts (Read more). A jQuery promise does not implement these interfaces so it won't work with that.

Here's a simple example using an ES6 promise:

function getStringFromWebServerAsync(url: string) {
    return new Promise<string>((resolve, reject) => {
        // note: could be written `$.get(url).done(resolve).fail(reject);`,
        //       but I expanded it out for clarity
        $.get(url).done((data) => {
            resolve(data);
        }).fail((err) => {
            reject(err);
        });
    });
}

async function asyncExample() { 
    try {
        const data = await getStringFromWebServerAsync("http://localhost/GetAString");
        console.log(data);
    }
    catch (err) {
        console.log(err);
    }
}

asyncExample();

Note that any code containing an await statement needs to be within an async function and so I have wrapped the code in one. That said, an upcoming proposal adds "top-level await", which will be available in TypeScript 3.8. Read more here and see here for TypeScript details.

David Sherret
  • 101,669
  • 28
  • 188
  • 178
15

Please note that you need to target ES6 in Typescript 1.7 to use async/await. With lower versions, Visual Studio outputs

TS1308 'await' expression is only allowed within an async function.

and

TS1311 Async functions are only available when targeting ECMAScript 6 and higher.

For more information see e.g. http://blogs.msdn.com/b/typescript/archive/2015/11/03/what-about-async-await.aspx

Zartag
  • 391
  • 4
  • 8
  • 8
    This is good information, but doesn't really answer the question. Perhaps it should be a comment, when you have enough reputation. – Heretic Monkey Mar 10 '16 at 22:57
  • 2
    I am pretty aware of it, but as you say I'm lacking the reputation. Sorry for that. – Zartag Mar 18 '16 at 17:07
  • Targeting ES6 has nothing to do with it, that's a syntax sugar setting. You need to specify that the ES6 promise feature is correct typing, which you do by including `ES2015.Promise` in `lib`, alternatively all of `ES6` which is what targeting ES6 does by default – CervEd Mar 16 '20 at 09:53