The awesome async/await syntax originally introduced by Microsoft in C# 4.5 is proposed as syntactic enhancement for ES7, the next JavaScript standard specification. While this feature will not be supported out of the box by browsers before at least a few years, it is however possible to start using today in your code with the help you great tools called transpilers, which translate your ES7 syntax into usable JavaScript supported by current browsers.
The setup is rather straightforward if you are using build tools like Webpack then you can integrate seamlessly the great Babel transpiler in your build process. Babel 6 has just been released and it now supports async/await keywords. For comprehensive details on how to integrate Babel with Webpack, I recommend taking a look at this article.
Now that you can automatically transpile your js code, let's take a look at how to add async/await to make your callbacks go away:
Let's use a viewer method that takes a callback as argument:
viewer.getProperties(dbId, cb)
The first step is to promisify that method. ES6 promises are also supported by Babel, so we can write the following code:
1 ///////////////////////////////////////////////////////////// 2 // Async wrapper for viewer.getProperties 3 // 4 ///////////////////////////////////////////////////////////// 5 viewer.getPropertiesAsync = function(dbId) { 6 7 return new Promise(function(resolve, reject) { 8 9 viewer.getProperties(dbId, function(result){ 10 11 if (result.properties) { 12 13 resolve(result.properties); 14 } 15 else { 16 17 reject(new Error('Error getting properties')); 18 } 19 }); 20 }); 21 }That's it, we can now asynchronously invoke our wrapper in an async prefixed method as follow:
1 ///////////////////////////////////////////////////////////// 2 // async method 3 // 4 ///////////////////////////////////////////////////////////// 5 async function dumpProperties(dbId) { 6 7 try { 8 9 let properties = await viewer.getPropertiesAsync(dbId); 10 11 properties.map((prop) => { 12 console.log(prop) 13 }); 14 } 15 catch(ex){ 16 17 console.log(ex); 18 } 19 }Pretty neat right? You can find tons of other articles about the async/await feature in ES7, here is one that I liked particularly. The full source code of my ES7 Async extension for the viewer is available below and you can also test a live version from my gallery (output is dumped to the browser console): Autodesk.ADN.Viewing.Extension.ES7Async
Comments
You can follow this conversation by subscribing to the comment feed for this post.