AI solution for Interview Question on BFE.dev
32. Explain `async` and `await`
async
and await
are keywords in JavaScript that are used to work with promises.
An async
function is a function that returns a promise. It can contain an await
expression that pauses the execution of the function until the promise is resolved. The await
keyword can only be used inside an async
function.
When an await
keyword is encountered, it stops the execution of the function until the promise is resolved. Once the promise is resolved, the function continues its execution, and the value of the resolved promise is returned.
async
and await
make asynchronous code easier to read and write. You can write asynchronous code that looks similar to synchronous code, making it easier to understand and maintain.
For example:
async function getData() {
const response = await fetch('https://example.com/data');
const data = await response.json();
return data;
}
In the above example, getData
is an async
function that fetches some data from a URL. The await
keyword is used to wait for the response to be returned before parsing it as JSON. Finally, the parsed JSON data is returned.
It's worth noting that async
and await
are not supported in all browsers, so you may need to use a transpiler like Babel to make sure your code works in all environments.