JavaScript is a single-threaded synchronous language, meaning it goes through the statements in the order they are written and processes one at a time.
console.log("cook!");
console.log("eat!");
console.log("clean!");
// cook!
// eat!
// clean!
If before the cook! operation there was an asynchronous operation like fetching the recipe from an API, the program might not wait for it to complete before moving on to the cook!, eat!, and clean! operations. This can result in out-of-order execution, like so:
fetchRecipeFromAPI(); // Assume this is an asynchronous function
console.log("cook!");
console.log("eat!");
console.log("clean!");
// Output might be:
// cook!
// eat!
// clean!
// (sometime later) Recipe fetched!
Well, we definitely need to get the recipe first, and then cook based on it!
To ensure the steps are executed in order, even if one of them is asynchronous, we can use async and await keywords. These little friends can help us write asynchronous code that appears synchronous, making it easier to understand and maintain.
There are 2 steps to use them:
- Define the asynchronous function with the async keyword before it.
- Use the await keyword inside your asynchronous function to pause the execution until the operation is completed.
In the following example:
- fetchRecipeFromAPI is an asynchronous function simulating a recipe fetch operation with a delay.
- cook is an asynchronous function that waits for fetchRecipeFromAPI to complete before continuing.
- main is an asynchronous function that ensures cook, eat!, and clean! happen in order.
async function fetchRecipeFromAPI() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Recipe fetched!");
resolve("recipe");
}, 2000); // Simulate an API call with a 2-second delay
});
}
async function cook(recipe) {
console.log("start cooking with", recipe);
}
async function main() {
const recipe = await fetchRecipeFromAPI(); // Wait for the recipe to be fetched
await cook(recipe); // Wait for the cooking to complete
console.log("eat!");
console.log("clean!");
}
main();
// Output:
// Recipe fetched!
// cook!
// start cooking with recipe
// eat!
// clean!
By using async and await, you ensure that the asynchronous cook function completes before moving on to eat! and clean!. This maintains the logical sequence of operations.
Note: If you try to get the value of an asynchronous function outside of it, It's always gonna be Promise { }, because JavaScript has no way of knowing what the result will be outside of that asynchronous process.
You can find the actual code in this SandBox
Top comments (0)