How to access return value of promise

How to Access Return Value of Promise

Promises are a way of handling asynchronous operations in JavaScript. They are used to handle operations that may take time to complete and return a value at some point in the future. Once the promise is resolved, it returns the value. To access the return value of a promise, we need to wait for the promise to resolve.

Using .then() Method

The most common way to access the return value of a promise is by using the .then() method. This method is called on the promise object and takes a function as an argument. This function will be called with the resolved value of the promise.


const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Hello, world!");
  }, 1000);
});

myPromise.then((result) => {
  console.log(result);
});

In this example, we create a new promise that resolves with the string "Hello, world!" after 1 second. We then call the .then() method on the promise object and pass in a function that logs the result to the console.

Using async/await Syntax

Another way to access the return value of a promise is by using the async/await syntax. This syntax allows us to write asynchronous code that looks like synchronous code.


async function myFunction() {
  const result = await myPromise;
  console.log(result);
}

myFunction();

In this example, we define an async function called myFunction() that awaits the resolved value of myPromise. The value is then logged to the console.

Using .catch() Method

If the promise rejects with an error, we can access the error message by using the .catch() method. This method is called on the promise object and takes a function as an argument. This function will be called with the error message.


const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("Oops, something went wrong!");
  }, 1000);
});

myPromise.catch((error) => {
  console.log(error);
});

In this example, we create a new promise that rejects with the string "Oops, something went wrong!" after 1 second. We then call the .catch() method on the promise object and pass in a function that logs the error to the console.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe