Categories
JavaScript Answers

How to Access the Resolved Value of a JavaScript Promise?

Spread the love

On many occasions, we want to get the resolved value of a JavaScript promise.

In this article, we’ll look at how to access the resolved value of a JavaScript promise.

Call then with a Callback

One way to get the value resolved value of a JavaScript promise it to call the then method with a callback that has one parameter.

The parameter has the resolved value.

For instance, we can write:

Promise.resolve(1)  
  .then((result) => {  
    console.log(result)  
  });

We call Promise.resolve to return a promise that resolved to 1.

Then we call then on it with a callback that has the result parameter.

result should have the resolved value of the promise.

And so the value of result is 1.

Using the async and await Syntax

We can also get the resolved value of a promise with the async and await syntax.

For instance, we can write:

(async () => {  
  const result = await Promise.resolve(1)  
  console.log(result)  
})()

We assign the resolved value of the promise with the await syntax to the result variable.

Therefore, result should also be 1 in this example.

await can only be used inside an async function.

Conclusion

We can get the resolved value of a JavaScript with the await keyword in an async function or call then with a callback that has the resolved value as the first parameter.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *