(This article written with the assistance of GitHub copilot AI.)
async and await are keywords in JavaScript that allow you to write asynchronous code in a more readable and concise way. They are based on promises, which are objects that represent the outcome of an asynchronous operation.
To use async and await, you need to declare a function with the async keyword, like this:
async function demoAsyncAwait() {
// some code
}
This means that the function will always return a promise, even if the return value is not a promise itself. For example, this function returns a promise that resolves to 1:
async function demoAsyncAwait() {
return 1;
}
Inside an async function, you can use the await keyword to pause the execution until a promise is settled, and then resume it with the promise result. For example, this function waits for one second and then returns “done!”:
async function demoAsyncAwait() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000);
});
let result = await promise; // wait until the promise resolves
return result; // "done!"
}
You can call an async function like any other function, but you need to use the .then method or another async function to get the result. For example, this code prints “done!” after one second:
demoAsyncAwait().then(console.log); // "done!"
Or, you can use another async function with await:
async function main() {
let result = await demoAsyncAwait(); // get the result of the async function
console.log(result); // "done!"
}
main();
Using async and await can make your code more readable and easier to follow, especially when you have multiple asynchronous operations that depend on each other. You can also use try/catch blocks to handle errors in async functions, instead of using .catch methods on promises.
If you want to learn more about async and await, you can check out these resources:
- Async/await – The Modern JavaScript Tutorial
- async function – JavaScript | MDN
- A Beginner’s Guide to JavaScript async/await, with Examples
- How to Use Async/Await in JavaScript – Explained with Code Examples
- Asynchronous programming in C# – C# | Microsoft Learn
Learn more