close

How to access the value of a promise?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to access the value of a promise? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to access the value of a promise ?

  1. How to access the value of a promise ?

    to access the value of a promise .then function of promiseB receives what is returned from .then function of promiseA.
    here promiseA is returning is a number, which will be available as number parameter in success function of promiseB. which will then be incremented by 1

  2. to access the value of a promise

    to access the value of a promise .then function of promiseB receives what is returned from .then function of promiseA.
    here promiseA is returning is a number, which will be available as number parameter in success function of promiseB. which will then be incremented by 1

Method 1

promiseA‘s then function returns a new promise (promiseB) that is immediately resolved after promiseA is resolved, its value is the value of the what is returned from the success function within promiseA.

In this case promiseA is resolved with a value – result and then immediately resolves promiseB with the value of result + 1.

Accessing the value of promiseB is done in the same way we accessed the result of promiseA.

promiseB.then(function(result) {
    // here you can use the result of promiseB
});

Edit December 2019async/await is now standard in JS, which allows an alternative syntax to the approach described above. You can now write:

let result = await functionThatReturnsPromiseA();
result = result + 1;

Now there is no promiseB, because we’ve unwrapped the result from promiseA using await, and you can work with it directly.

However, await can only be used inside an async function. So to zoom out slightly, the above would have to be contained like so:

async function doSomething() {
    let result = await functionThatReturnsPromiseA();
    return result + 1;
}

Method 2

.then function of promiseB receives what is returned from .then function of promiseA.

here promiseA is returning is a number, which will be available as number parameter in success function of promiseB. which will then be incremented by 1

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment