async/await support in ES6 targets (Node v4+)

TypeScript now supports asynchronous functions for engines that have native support for ES6 generators, e.g. Node v4 and above.Asynchronous functions are prefixed with the async keyword; await suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the Promise returned.

Example

In the following example, each input element will be printed out one at a time with a 200ms delay:

  1. "use strict";
  2. // printDelayed is a 'Promise<void>'
  3. async function printDelayed(elements: string[]) {
  4. for (const element of elements) {
  5. await delay(200);
  6. console.log(element);
  7. }
  8. }
  9. async function delay(milliseconds: number) {
  10. return new Promise<void>(resolve => {
  11. setTimeout(resolve, milliseconds);
  12. });
  13. }
  14. printDelayed(["Hello", "beautiful", "asynchronous", "world"]).then(() => {
  15. console.log();
  16. console.log("Printed every element!");
  17. });

For more information see Async Functions blog post.