How to work with asynchronous JavaScript? What is the difference between Promise and async/await?
sobes.tech AI
Answer from AI
Asynchronous JavaScript allows performing operations that take time (such as server requests) without blocking the main execution thread.
Promise is an object that represents the result of an asynchronous operation and can be in three states: pending, fulfilled successfully, or rejected with an error. You can handle the result or error using .then() and .catch() methods.
async/await is syntactic sugar over Promise, which allows writing asynchronous code in a synchronous style, making it more readable and understandable. A function declared with async returns a Promise, and await pauses execution until the Promise is resolved.
Example with Promise:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Same with async/await:
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
getData();
The main difference is that async/await makes the code more linear and easier to read, especially when chaining asynchronous operations.