how to catch a promise in javascript

A promise in JavaScript is a special object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises allow you to write asynchronous code that looks and behaves like synchronous code.

To catch a promise in JavaScript, you need to use the .then() and .catch() methods. Here's an example:

index.tsx
function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data received');
    }, 2000);
  });
}

getData().then(data => {
  console.log(data);
}).catch(error => {
  console.error('Error:', error);
});
247 chars
14 lines

In the above example, getData() returns a new Promise. The then() method is called on the Promise object to handle the data returned by the successful completion of the Promise. The catch() method is called to handle any errors that occurred during the Promise execution.

You can also use the async/await syntax to catch a Promise in JavaScript. Here's an example:

index.tsx
async function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data received');
    }, 2000);
  });
}

async function main() {
  try {
    const data = await getData();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

main();
309 chars
19 lines

In the above example, the getData() function returns a new Promise. The try/catch block is used to handle the success or failure of the Promise execution. The await keyword is used to wait for the Promise to settle and the resulting value is assigned to the data variable.

Using the .then() and .catch() methods or the async/await syntax allows you to handle the success or failure of a Promise in JavaScript.

gistlibby LogSnag