Jun
Understanding async-await in JavaScript
The Asynchronous events in JavaScript are the events that occur outside of the normal programming flow. For example: when a user clicks on a button, or when the data is received from the API call, JavaScript executes the next instructions of the program without blocking the programming flow in the wait for asynchronous code to be resolved.
But sometimes there is a dependency on the data retrieved from async calls to perform some actions.
CallBacks:
The first and most intuitive way of handling these scenarios is by using the callbacks.
A callback is a function that is executed after some tasks are finished.
Whenever we need to do something after the completion of some async code block we can use callBack Functions.
getJSON('path/emp_of_the_month', (error, employeeId) => { getJSON('path/employee_details/'+employeeId, (error, details) => { getJSON('path/send_prize/' + details.address, (error, status) => { if (status) { console.log("Prize Sent"); } }); }); });
In the above code, each new request is dependent on the result of the previous asynchronous response, so we could not fetch the result of the second request before completing the first and so on.
So, we had to pass a callback function to each request so that the callback can run after completing the async request.
The problem with the code above is that it’s quite messy, we call it a callback hell.
Another way to write the code above is with the use of Promises.
Promises:
Promise basically gives us a value that we can use as any other variable, and when a promise is resolved its then method will be executed. This way we can write the above code in a much simpler way.
getJSON("path/emp_of_the_month") .then(employeeId => getJSON('path/employee_details/'+employeeId)) .then(details => getJSON('path/send_prize/' + details.address)) .then(status => {if (status) { console.log('Prize sent') }}); But still there is quite a lot of code for handling interdependent requests. What we actually want is a code sequential: function inValidButDesiredCode () { var employeeId = getJSON("path/emp_of_the_month"); var details = getJSON('path/employee_details/'+employeeId); var status = getJSON('path/send_prize/' + details.address); if (status) { console.log('Prize Sent'); } }
We know the code in the above function won’t work, because JavaScript won’t wait for employeeId to get resolved before calling the next getJSON request.
async-await:
Luckily, JavaScript provides a way to write async code sequentially using two keywords: async and await.
The keyword await will stop JavaScript from executing the next line in async marked function unless the statement with await keyword is resolved.
To handle the Promise Errors we can simply put this code in try catch Blocks.
async function validAndDesiredCode () { try { var employeeId = await getJSON("path/emp_of_the_month"); var details = await getJSON('path/employee_details/'+employeeId); var status = await getJSON('path/send_prize/' + details.address); if (status) { console.log('Prize Sent'); } }catch(error) { console.log(error); } }
If you want to hire a Javascript developer, Ficode is here to help you so please don’t hesitate to contact us today at info@ficode.com.