Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the async/await syntax work in TypeScript?

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.

like image 679
Pranay Dutta Avatar asked Sep 04 '15 15:09

Pranay Dutta


People also ask

How does async await work TypeScript?

async/await is essentially a syntactic sugar for promises, which is to say the async/await keyword is a wrapper over promises. An async function always returns a promise. Even if you omit the Promise keyword, the compiler will wrap your function in an immediately resolved promise.

What is the syntax of writing async await?

The syntax: // works only inside async functions let value = await promise; The keyword await makes JavaScript wait until that promise settles and returns its result.

How does async await work?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.

What is await syntax?

Await SyntaxThe keyword await before a function makes the function wait for a promise: let value = await promise; The await keyword can only be used inside an async function.


1 Answers

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.

like image 172
David Sherret Avatar answered Sep 24 '22 11:09

David Sherret