How does the async/await syntax work in TypeScript?
Asked Answered
P

2

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.

Pogge answered 4/9, 2015 at 15:33 Comment(10)
See Proposal: Async Functions on TypeScript github.com/Microsoft/TypeScript/issues/1664. Also smellegantcode.wordpress.com/2015/02/01/… and dotnetcurry.com/javascript/1131/…Dona
The roadmap shows async/await as 2.0: github.com/Microsoft/TypeScript/wiki/Roadmap (as of July 23rd)Jabe
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'sPogge
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.Jabe
@JonSkeet it is ,as an experimental feature of 1.6 github.com/Microsoft/TypeScript/wiki/…Pogge
@JonSkeet it's experimental in 1.6 with the --experimentalAsyncFunctions compiler option (and 1.6 beta was just released on wednesday)Cosmopolitan
@DavidSherret: Makes sense.Jabe
@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...)Jabe
@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)Pogge
now, that 1.7 is released and contains this feature, I changed the tag to 1.7Comorin
C
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.

Cosmopolitan answered 9/10, 2015 at 1:45 Comment(0)
S
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

Smaltite answered 20/12, 2015 at 18:19 Comment(3)
This is good information, but doesn't really answer the question. Perhaps it should be a comment, when you have enough reputation.Standoffish
I am pretty aware of it, but as you say I'm lacking the reputation. Sorry for that.Smaltite
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 defaultMontana

© 2022 - 2024 — McMap. All rights reserved.