Middle+
How to make try/catch construct work with Promise? How to make Promise synchronous using async/await?
sobes.tech AI
Answer from AI
To make a try/catch construct work with Promise, you need to use the async/await keywords. Regular Promises are handled through the .then() and .catch() methods, but for convenience and more readable code, you can wrap the Promise call in an async function and use await, which allows you to write asynchronous code in a synchronous style.
Example:
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 loading data:', error);
}
}
fetchData();
Here, await "pauses" the execution of the function until the Promise is resolved, and errors occurring inside the Promise are caught in the catch block. Thus, the Promise appears "synchronous" in perception, although it remains asynchronous under the hood.