Reading codebases and seeing async/await in functions may look a little tricky. With this article, you will see how they work and notice that it is a clever, easier way to work with asynchronous functions.
Prerequisites 📝
- A working knowledge of promises (I will give a quick refresher, if you do not remember!)
- A working knowledge of try/catch
- A code editor (I recommend Visual Studio Code)
Let's Get Started ✨
First, let's breakdown the async keyword
When you see the async keyword before a function, this means that the function is going to return a promise. (here's the refresher!!!) A promise, in simple terms, is an object that contains the results of the eventual completion or failure of an asynchronous operation. Let's see it in action,
async function brewCoffee() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("coffee is done! enjoy :)"), 2000)
});
try {
let coffee = await promise;
console.log(coffee);
} catch(error) {
console.log('error', error);
}
}
brewCoffee();
//output: coffee is done! enjoy :)
The function brewCoffee
starts with a promise that will resolve after 2 seconds. That promise will be assigned to the variable coffee
which will be printed out. If the promise is rejected, the error will be printed out in the catch.
How does await play a role?
The await
keyword will pause the execution of the function so the promise can resolve.
How they both work together
The await
keyword is declared in the async
function. Often, you will see async/await
in API calls. This will make sure the data is correctly fetched before other lines of code are called. For example,
async function fetchCappiccunoRecipe() {
const response = await fetch('https://api.sampleapis.com/coffee/hot');
const recipe = await response.json();
return recipe;
}
function makeCoffee(recipe) {
console.log('The coffee was made with this ', recipe);
}
async function barista() {
const recipe = await fetchCappiccunoRecipe();
makeCoffee(recipe);
}
barista();
When the barista
function is called, the recipe will be fetched which will be passed in as a parameter in the makeCoffee
function.
Key Takeaways ✨
async/await
will make your code easier to work with, especially since it makes it more readable. It is also a more concise way of writing asynchronous functions. Alternatively, it could have been written like this,
function fetchCappiccunoRecipe() {
return fetch('https://api.sampleapis.com/coffee/hot');
}
function makeCoffee(recipe) {
console.log('The coffee was made with this ', recipe);
}
function barista() {
fetchCappiccunoRecipe().then((response) => {
response.json().then((recipe) => {
makeCoffee(recipe);
});
});
}
barista();
You can see that there is more nesting and callback functions. Overall, a more confusing experience.
Next Steps ✨
There may be opportunities in your code base to refactor functions to use async/await
. I recommend this article on migrating promises into async/await
functions: https://afteracademy.com/blog/migrating-from-promise-chains-to-async-await/ if you need additional guidance! Thanks for reading and happy coding :)
Top comments (0)