- async and await: If you have any experience with the .NET world like me, you will find this extremely familiar. Although there may be some variations but it is much easier to understand if you already have some experience in C#. Do not get me wrong, it does not mean that people without C# experience will not get this, it is just that people with C# experience will feel a lot closer to home than others.
Up to until ES 2016, this is how we made an asynchronous call using promises.
In case you are not familiar with arrow functions and ES 2015, no need to worry as I have given the same implementation using ES 5 below, although you need to have some background with promises. You can skip the below image if you are comfortable with the one above.
If I make the same implementation using the new async and await keyword in ES 2017, it would look something like this.
You can see the actual pen here
This is how you can make an asynchronous call, without having to do download any external libraries by making an xhr ‘GET’ request to the github api.
‘asynchrony.js’ is the file in my case.
Simply walking through the code, here we have just made a function called ‘asyncFn’ which just makes a GET request to the github api’s user resource to fetch my details and the response is returned inside of the ‘getMe’ function as a json object which is logged to the console.
Now, if we remove the await keyword in line 30, the ‘asyncFn’ will simply return a promise to which a resolve and a reject handler can be attached by using the ‘then’ and ‘catch’ handlers respectively, so your ‘getMe’ function becomes something like this
So, using await resolves your promises to the appropriate response object which can be a proper response when resolved and an erroneous response when rejected by the ‘asyncFn’.
Things to note:
a) You cannot use an await inside of a function unless that function is marked with async keyword.