{"id":2201,"date":"2015-11-03T12:53:23","date_gmt":"2015-11-03T20:53:23","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/typescript\/?p=2201"},"modified":"2019-04-30T13:04:17","modified_gmt":"2019-04-30T21:04:17","slug":"what-about-async-await","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/typescript\/what-about-async-await\/","title":{"rendered":"What about Async\/Await?"},"content":{"rendered":"<p>We\u2019ve heard your feedback that you\u2019re excited about async\/await in TypeScript. Async\/await allows developers to write to asynchronous code flows as if they were synchronous, removing the need for registering event handlers or writing separate callback functions. You may have seen similar patterns in C#. TypeScript\u2019s async\/await pattern makes use of Promises, much <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/vstudio\/hh191443(v=vs.110).aspx\">like C#\u2019s async\/await pattern<\/a> leverages Tasks. <a href=\"http:\/\/www.html5rocks.com\/en\/tutorials\/es6\/promises\/\">Promises<\/a> are objects that represent ongoing asynchronous actions and are a built-in feature of ECMAScript 6 (ES6). TypeScript\u2019s async\/await is implemented as <a href=\"http:\/\/tc39.github.io\/ecmascript-asyncawait\/\">proposed for ES2016 (aka ES7)<\/a>.<\/p>\n<p>We\u2019re happy to announce that you can already use async\/await today if you\u2019re targeting Node.js v4 or later! In this post, we\u2019ll show you how and give you an update on async\/await\u2019s progress.<\/p>\n<p><strong>How async\/await works<\/strong><\/p>\n<p>JavaScript is single-threaded and sequential: once your function starts running, it can\u2019t be interrupted before it runs to completion. For most tasks, this is exactly what the developer expects and wants. However, when an asynchronous task (such as a call to a web service) is running, it\u2019s more efficient to allow the rest of the JavaScript to continue running while you wait for the task to return. Async\/await allows you to call asynchronous methods much the same way you\u2019d call a synchronous method, but without blocking for the asynchronous operations to complete.<\/p>\n<p>For example, in the code below, <span style=\"font-family: 'courier new', courier;\">main<\/span> awaits on the result of the asynchronous function <span style=\"font-family: 'courier new', courier;\">ping<\/span>. Because <span style=\"font-family: 'courier new', courier;\">main<\/span> awaits, it\u2019s declared as an async function. The <span style=\"font-family: 'courier new', courier;\">ping<\/span> function awaits on the <span style=\"font-family: 'courier new', courier;\">delay<\/span> function in a loop, so it\u2019s declared as async as well. The <span style=\"font-family: 'courier new', courier;\">delay<\/span> function calls <span style=\"font-family: 'courier new', courier;\">setTimeout<\/span> to return a Promise after a certain amount of time. When <span style=\"font-family: 'courier new', courier;\">setTimeout<\/span>\u2019s promise returns, you\u2019ll see \u2018ping\u2019 on the console.<\/p>\n<p><span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">async<\/span> <span style=\"color: #0000ff;\">function<\/span> main() {<\/span>\n<span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">\u00a0await<\/span> ping();<\/span>\n<span style=\"font-family: 'courier new', courier;\">}<\/span><\/p>\n<p><span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">async<\/span> <span style=\"color: #0000ff;\">function<\/span> ping() {<\/span>\n<span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">\u00a0for<\/span> (<span style=\"color: #0000ff;\">var<\/span>\u00a0i = 0; i &lt; 10; i++) {<\/span>\n<span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">\u00a0\u00a0await<\/span> delay(300);<\/span>\n<span style=\"font-family: 'courier new', courier;\">\u00a0\u00a0console.log(&#8220;ping&#8221;);<\/span>\n<span style=\"font-family: 'courier new', courier;\">\u00a0}<\/span>\n<span style=\"font-family: 'courier new', courier;\">}<\/span><\/p>\n<p><span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">function<\/span> delay(ms: <span style=\"color: #0000ff;\">number<\/span>) {<\/span>\n<span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">\u00a0return<\/span> <span style=\"color: #0000ff;\">new<\/span> Promise(resolve =&gt; setTimeout(resolve, ms));<\/span>\n<span style=\"font-family: 'courier new', courier;\">}<\/span><\/p>\n<p><span style=\"font-family: 'courier new', courier;\">main();<\/span><\/p>\n<p>&nbsp;<\/p>\n<p>TypeScript uses <a href=\"http:\/\/www.ecma-international.org\/ecma-262\/6.0\/#sec-generator-function-definitions\">ES6 generators<\/a> to implement the ability to re-enter a function at a given point when an asynchronous call returns. Generators use the <span style=\"font-family: 'courier new', courier;\">yield<\/span> keyword to tell the JavaScript runtime when control is being given up while a function waits for something to happen. When that something happens, the JavaScript runtime then continues the function execution from where control was yielded. For the sample above, the TypeScript compiler emits the below ES6 JavaScript for the <span style=\"font-family: 'courier new', courier;\">ping<\/span> function.<\/p>\n<p><span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">function<\/span> ping() {<\/span>\n<span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">\u00a0return<\/span> __awaiter(<span style=\"color: #0000ff;\">this<\/span>, <span style=\"color: #0000ff;\">void<\/span> 0, Promise, <span style=\"color: #0000ff;\">function<\/span>* () {<\/span>\n<span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">\u00a0\u00a0for<\/span> (<span style=\"color: #0000ff;\">var<\/span>\u00a0i = 0; i &lt; 10; i++) {<\/span>\n<span style=\"font-family: 'courier new', courier;\"><span style=\"color: #0000ff;\">\u00a0\u00a0\u00a0yield<\/span> delay(300);<\/span>\n<span style=\"font-family: 'courier new', courier;\">\u00a0\u00a0\u00a0console.log(<span style=\"color: #993300;\">&#8220;ping&#8221;<\/span>);<\/span>\n<span style=\"font-family: 'courier new', courier;\">\u00a0\u00a0}<\/span>\n<span style=\"font-family: 'courier new', courier;\">\u00a0});<\/span>\n<span style=\"font-family: 'courier new', courier;\">}<\/span><\/p>\n<p>The<span style=\"font-family: 'courier new', courier;\">__awaiter<\/span> function wraps the function body, including the <span style=\"font-family: 'courier new', courier;\">yield<\/span> statement, in a Promise that executes the function as a generator.<\/p>\n<p><strong>Trying it out with Node.js<\/strong><\/p>\n<p><span lang=\"EN\">Starting with nightly builds, TypeScript 1.7 now supports async\/await for ES6 targets. You can install the latest nightly build of TypeScript using <\/span><span lang=\"EN\" style=\"font-family: courier new,courier;\">npm install typescript@next<\/span><span lang=\"EN\"> and try it with Node.js v4 or beyond, which has support for ES6 generators. Here\u2019s how your <\/span><span style=\"font-family: courier new,courier;\">tsconfig.json<\/span> would look like:<\/p>\n<pre><span style=\"font-family: 'courier new', courier;\"><span style=\"color: #008080;\">\"compilerOptions\"<\/span>: {<\/span>\r\n<span style=\"font-family: 'courier new', courier;\"><span style=\"color: #008080;\">\u00a0 \"target\"<\/span>: <span style=\"color: #993300;\">\"ES6\"<\/span>,<\/span>\r\n<span style=\"font-family: 'courier new', courier;\"><span style=\"color: #008080;\">\u00a0 \"module\": <span style=\"color: #993300;\">\"commonjs\"<\/span><\/span><\/span>\r\n<span style=\"font-family: 'courier new', courier;\">}<\/span><\/pre>\n<p>The compiled JavaScript output can then run in Node.js:<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-2203\" src=\"https:\/\/devblogs.microsoft.com\/typescript\/wp-content\/uploads\/sites\/11\/2015\/11\/8420.ping_.png\" alt=\"\" width=\"907\" height=\"503\" srcset=\"https:\/\/devblogs.microsoft.com\/typescript\/wp-content\/uploads\/sites\/11\/2015\/11\/8420.ping_.png 907w, https:\/\/devblogs.microsoft.com\/typescript\/wp-content\/uploads\/sites\/11\/2015\/11\/8420.ping_-300x166.png 300w, https:\/\/devblogs.microsoft.com\/typescript\/wp-content\/uploads\/sites\/11\/2015\/11\/8420.ping_-768x426.png 768w\" sizes=\"(max-width: 907px) 100vw, 907px\" \/><\/p>\n<p>If you\u2019re targeting Node.js v4 or later, try out async\/await today. We\u2019ve created a more complex sample using the GitHub API to asynchronously retrieve history on a repo. You can find the source on the <a href=\"https:\/\/github.com\/Microsoft\/TypeScriptSamples\/tree\/master\/async\">TypeScriptSamples repo<\/a> and run it in Node.js. We\u2019d love to hear your feedback and\u00a0if you find <a href=\"https:\/\/github.com\/Microsoft\/TypeScript\/issues\/\">issues, please let us know<\/a>. One other thing to keep in mind: Node.js doesn\u2019t yet support ES6 modules, so choose CommonJS module output when compiling your TypeScript<span lang=\"EN\">, as indicated in the <span style=\"font-family: courier new,courier;\">tsconfig.json<\/span> above<\/span><span lang=\"EN\">.<\/span><\/p>\n<p><strong>Next steps<\/strong><\/p>\n<p>We know that many TypeScript developers want to write async\/await code for browsers as well as for Node.js and understand that using a temporary solution based on additional transpiliation layer is not optimal either from a developer workflow perspective or due to the performance impact it causes with the extra compilation overhead. To target the breadth of browsers, we need to rewrite ES6 generator functions into ES5-executable JavaScript using a state machine. It\u2019s a big challenge that requires significant changes across the compiler, but we\u2019re working on it. Stay tuned; we\u2019ll keep you up to date on our progress!<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We\u2019ve heard your feedback that you\u2019re excited about async\/await in TypeScript. Async\/await allows developers to write to asynchronous code flows as if they were synchronous, removing the need for registering event handlers or writing separate callback functions. You may have seen similar patterns in C#. TypeScript\u2019s async\/await pattern makes use of Promises, much like C#\u2019s [&hellip;]<\/p>\n","protected":false},"author":378,"featured_media":1797,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-2201","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-typescript"],"acf":[],"blog_post_summary":"<p>We\u2019ve heard your feedback that you\u2019re excited about async\/await in TypeScript. Async\/await allows developers to write to asynchronous code flows as if they were synchronous, removing the need for registering event handlers or writing separate callback functions. You may have seen similar patterns in C#. TypeScript\u2019s async\/await pattern makes use of Promises, much like C#\u2019s [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/posts\/2201","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/users\/378"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/comments?post=2201"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/posts\/2201\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/media\/1797"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/media?parent=2201"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/categories?post=2201"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/tags?post=2201"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}