how to fetch promise object from function in javascript

To fetch a promise object returned from a function in JavaScript, you can use the then() method or the await keyword. Here's an example using both approaches:

index.tsx
// Function that returns a promise
function fetchData() {
  return new Promise((resolve, reject) => {
    // Some asynchronous task
    setTimeout(() => {
      const data = [1, 2, 3, 4, 5];
      if (data) {
        resolve(data);
      } else {
        reject("Data not found");
      }
    }, 2000);
  });
}

// Using then()
fetchData().then((data) => {
  console.log(data);
}).catch((error) => {
  console.error(error);
});

// Using async/await
async function getData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

getData();
608 chars
34 lines

In the above example, the fetchData() function returns a promise object. We can use the then() method to handle the resolved value or the catch() method to handle any errors.

Alternatively, we can use the async/await syntax to handle the promise. We declare an async function and use the await keyword to wait for the promise to resolve. We also wrap the await call in a try-catch block to handle any errors that might occur.

gistlibby LogSnag