In the next video, you’ll look at an example code with Srishti to dig deeper into the async & await keywords.
In the last video, you looked at how you can convert an asynchronous code written using promises into the code utilizing async function and using await inside it to wait for the promise to be resolved or rejected.
Following is the code you looked at, which is written using async & await:
CASE A: When the promise is RESOLVED
// defining the async function which waits for the promise to be resolved / rejected const getName = async () => { try { let name = await namePromise; console.log(`Name received from DB = ${name}`); } catch (err) { console.log(err); } } // defining the promise object with the producer let namePromise = new Promise((resolve, reject) => { console.log("Getting name from DB..."); setTimeout(() => { resolve("Srishti"); }, 3000); }); getName();
When the promise is resolved, the result passed in as an argument while invoking the resolve() callback method is contained inside the variable which holds the result of the promise, which is waited for. In this case, the variable name will hold the result when the namePromise is resolved.
Output:
Getting name from DB...
Name received from DB = Srishti
CASE B: When the promise is REJECTED
// defining the async function which waits for the promise to be resolved / rejected const getName = async () => { try { let name = await namePromise; console.log(`Name received from DB = ${name}`); } catch (err) { console.log(err); } } // defining the promise object with the producer let namePromise = new Promise((resolve, reject) => { console.log("Getting name from DB..."); setTimeout(() => { reject(new Error("Error getting name!")); }, 3000); }); getName();
Output:
Getting name from DB... Error: Error getting name! at setTimeout
When the promise is rejected (or if an error occurred in the producer code) in the try block, the control goes to the catch block and the code inside it is executed.
Now is the time for an exercise based on whatever you have learned until now about async & await. Watch the next video to look at the exercise.