Middle
How to get the value from a Promise and handle errors?
sobes.tech AI
Answer from AI
To get a value from a Promise and handle errors in JavaScript, the .then() method is used for successful results and .catch() for errors. You can also use async/await with a try/catch block.
Example with .then() and .catch():
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error:', error);
});
Example with async/await:
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log('Data:', data);
} catch (error) {
console.error('Error:', error);
}
}
getData();