The Async/Await functionality has been around since TypeScript 1.7 but back then it was only available for the ES6/ES2016 runtime. Since TypeScript 2.1, async/await works for ES5 and ES3 runtimes as well, which is very good news. I am kicking myself that I did not start using it sooner.
As with anything new I learn, I have tried to apply it to SharePoint as well to see how I can improve my development experience. Turns out using async/await can really make your SharePoint Framework code simpler and more readable. Lets have a look at some examples and compare between using Promises and Async/Await in your code.
Also, an important thing to note is that although I am making comparisons between using Promises and using async/await, ultimately the aync/await code is downleveled to using Promises by the typescript compiler. If the runtime does not have a native Promise object, we should make sure we have the right polyfills available.
The comparison here is more around code readability and conciseness.
All the code I am using is running inside a SharePoint Framework webpart. So, when you see the 'this' keyword in the code, it refers to my SPFx webpart which inherits from the BaseClientSideWebPart class. Since I am calling the code from inside my webpart, I have access to 'this'.
Here is my import statements for the code:
Simple example using Promises and 'then' callbacks:
Same code using async/await:
Here is a slightly more complex example with code which accepts an array of SharePoint login names and uses the batching framework to get the user profile properties of each user in the array.
You will need the IPerson interface for this:
Complex example using Promises and 'then' callbacks:
Same code using async/await:
As you can see, there is significantly less callbacks when using async/await and the code is also a lot more readable.
Hope you found this post useful. Thanks for reading!
3 comments:
really good stuff! Thanks mate!
Really handy. We're hitting a wall calling an async function to get subsite recursively (to get it's subsites of it's subsite, etc...). using await should help us at keep clean code and see what we're trying to achieve rather than dying in callbacks/promises. we're building an object up with teh structure rather than just consoling or outputting, so we're breaking out of async at points to get the new objects and add it's children etc... with all the promises it's seriously hard to read!
This looks like it will make the code readable, which is half the battle - staying on top of what you are actually trying to do!
Excellent. Thank you!
Post a Comment