The async
and await
keywords are used in asynchronous programming in order to make the code easier to read and write. async
is used to define a function as asynchronous, and await
is used to wait for a promise to be resolved within an asynchronous function.
Here’s an example of how you might use these keywords:
async function getData() {
const response = await fetch('https://some-url.com/data');
const data = await response.json();
return data;
}
In this example, the getData()
function is asynchronous, and it uses the await
keyword to wait for the promise returned by the fetch()
function to be resolved. This allows the code to be written in a more synchronous-looking style, which can make it easier to read and understand.
It’s important to note that the await
keyword can only be used within an async
function. Also, when you await
a promise, the code execution is paused until the promise is resolved. This means that if you await
a long-running operation, your code will be blocked until the operation is complete.