Junior — Middle
What is the purpose of the async and await constructs in programming?
sobes.tech AI
Answer from AI
The async and await constructs are used for working with asynchronous code, allowing it to be written in a style similar to synchronous code, which simplifies reading and maintenance.
asyncbefore a function indicates that the function returns a promise and can contain asynchronous operations.awaitis used inside anasyncfunction to wait for the result of a promise, pausing the execution until the promise is resolved, but not blocking the thread.
Example in JavaScript (Node.js):
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
This approach simplifies handling asynchronous operations compared to using .then() chains.