In the segment on promises, you looked at how they can help you solve the problem with callback hell. Following is the code which you looked at when using promises in place of nested callbacks:
Code Snippet *:
// USING PROMISES // function to fetch details of user in Student Management System const fetchUserDetails = (username, password) => { database.authenticateUser(username, password) .then(userInfo => dataBase.getRoles(userInfo)) .then(rolesInfo => dataBase.getPermissions(rolesInfo)) .then(permissionsInfo => { // code written inside the function named 'callback' }) .catch((err) => { // code to handle error }); };
* Now is the time to convert the code written using promises and witness how the new syntax using async & await makes it even to write & maintain the code. Watch the next video to see how Srishti converts the above code using async & await keywords.
Following is the code which utilizes async & await syntax in ES8 and thus, makes the above code written using promises even more readable and manageable:
Code Snippet:
const fetchUserDetails = async (username, password) => { try { const userInfo = await dataBase.authenticateUser(username, password); const rolesInfo = await dataBase.getRoles(userInfo); const permissionsInfo = await dataBase.getPermissions(rolesInfo); } catch (e) { //code to handle error } };
In the section of promises, you looked at another example with Sakshi of using promises to solve the problem with callback hell. Let us look at that example too and see how the code with promises can be re-written using async & await keywords.
Alright, seems like using async & await is the best way to deal with asynchronous behaviour in JavaScript until something next comes up in JavaScript!