Typescript 1.6 – Async & Await

in Front-End Web Technologies

The Promise pattern simplifies JavaScript asynchronous function management

While using promises is much cleaner than using naive callbacks the code still does not look so nice and tidy

Consider the following,

function getValue() {
	return asyncStep1().then(function () {
		return asyncStep2().then(function () {
			return asyncStep3();
		});
	});
}

The sample code invokes three asynchronous functions one after the other and returns the output of the last function (step3)

Using Typescript 1.6 you can just write the following

async function getValue() {
    await asyncStep1();
    await asyncStep2();
    return await asyncStep3();
}

Much better, right ?

The async feature is considered experimental which means that it is turned off by default.

If you are using Typescript from the command line (using NodeJS) then you need to add the –experimentalAsyncFunctions option

In case you are compiling Typescript within VisualStudio 2015 then you need to fix your .csproj file

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
  <TypeScriptTarget>ES6</TypeScriptTarget>
  <TypeScriptJSXEmit>None</TypeScriptJSXEmit>
  <TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
  <TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
  <TypeScriptModuleKind>None</TypeScriptModuleKind>
  <TypeScriptRemoveComments>False</TypeScriptRemoveComments>
  <TypeScriptOutFile />
  <TypeScriptOutDir />
  <TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
  <TypeScriptNoEmitOnError>True</TypeScriptNoEmitOnError>
  <TypeScriptSourceMap>True</TypeScriptSourceMap>
  <TypeScriptMapRoot />
  <TypeScriptSourceRoot />
  <TypeScriptExperimentalAsyncFunctions>true</TypeScriptExperimentalAsyncFunctions>
</PropertyGroup>

BTW, if you are a C# programmer than you probably think that this is quite boring since C# offers the async & await keywords for more than 5 years. Well, I guess that you are correct, but still it is quite amazing to think that JavaScript is going to be as rich as C# and even richer …

Contact us
You might also like
Share: