[javascript] How to access the value of a promise?

I'm looking at this example from Angular's docs for $q but I think this probably applies to promises in general. The example below is copied verbatim from their docs with their comment included:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved and its value
// will be the result of promiseA incremented by 1

I'm not clear how this works. If I can call .then() on the result of the first .then(), chaining them, which I know I can, then promiseB is a promise object, of type Object. It is not a Number. So what do they mean by "its value will be the result of promiseA incremented by 1"?

Am I supposed to access that as promiseB.value or something like that? How can the success callback return a promise AND return "result + 1"? I'm missing something.

This question is related to javascript angularjs promise angular-promise

The answer is


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 2019: async/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;
}

In the Node REPL, to get a DB connection that was the value of a promise, I took the following approach:

let connection
try {
  (async () => {
    connection = await returnsAPromiseResolvingToConnection()
  })()
} catch(err) {
  console.log(err)
}

The line with await would normally return a promise. This code can be pasted into the Node REPL or if saved in index.js it can be run in Bash with

node -i -e "$(< index.js)"

which leaves you in the Node REPL after running the script with access to the set variable. To confirm that the asynchronous function has returned, you can log connection for example, and then you're ready to use the variable. One of course wouldn't want to count on the asynchronous function being resolved yet for any code in the script outside the asynchronous function.


I am a slow learner of javascript promises, by default all async functions return a promise, you can wrap your result as:

(async () => {
//Optional "await"
  await yourAsyncFunctionOrPromise()
    .then(function (result) {
      return result +1;
    })
    .catch(function (error) {
      return error;
    })()
})

"The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise. If the Promise is rejected, the await expression throws the rejected value."

Read more about await and promises at MDN Web Docs


This example I find self-explanatory. Notice how await waits for the result and so you miss the Promise being returned.

cryA = crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
PromiseĀ {<pending>}
cryB = await crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
{publicKey: CryptoKey, privateKey: CryptoKey}

pixelbits answer is correct and you should always use .then() to access the value of a promise in production code.

However, there is a way to access the promise's value directly after it has been resolved by using the following unsupported internal node.js binding:

process.binding('util').getPromiseDetails(myPromise)[1]

WARNING: process.binding was never meant to be used outside of nodejs core and the nodejs core team is actively looking to deprecate it

https://github.com/nodejs/node/pull/22004 https://github.com/nodejs/node/issues/22064


Maybe this small Typescript code example will help.

private getAccount(id: Id) : Account {
    let account = Account.empty();
    this.repository.get(id)
        .then(res => account = res)
        .catch(e => Notices.results(e));
    return account;
}

Here the repository.get(id) returns a Promise<Account>. I assign it to the variable account within the then statement.


Parsing the comment a little differently than your current understanding might help:

// promiseB will be resolved immediately after promiseA is resolved

This states that promiseB is a promise but will be resolved immediately after promiseA is resolved. Another way of looking at this means that promiseA.then() returns a promise that is assigned to promiseB.

// and its value will be the result of promiseA incremented by 1

This means that the value that promiseA resolved to is the value that promiseB will receive as its successCallback value:

promiseB.then(function (val) {
  // val is now promiseA's result + 1
});

.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


There are some good answer above and here is the ES6 Arrow function version

var something = async() => {
   let result = await functionThatReturnsPromiseA();
   return result + 1;
}

When a promise is resolved/rejected, it will call its success/error handler:

var promiseB = promiseA.then(function(result) {
   // do something with result
});

The then method also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.

There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:

1. Return nothing --> PromiseB is resolved immediately, 
   and undefined is passed to the success handler of promiseB
2. Return a value --> PromiseB is resolved immediately,
   and the value is passed to the success handler of promiseB
3. Return a promise --> When resolved, promiseB will be resolved. 
   When rejected, promiseB will be rejected. The value passed to
   the promiseB's then handler will be the result of the promise

Armed with this understanding, you can make sense of the following:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

The then call returns promiseB immediately. When promiseA is resolved, it will pass the result to promiseA's success handler. Since the return value is promiseA's result + 1, the success handler is returning a value (option 2 above), so promiseB will resolve immediately, and promiseB's success handler will be passed promiseA's result + 1.


promiseA(pram).then(
     result => { 
     //make sure promiseA function allready success and response
     //do something here
}).catch(err => console.log(err)) => {
     // handle error with try catch
}

You can easily do that using an async wait method in javascript.

Below is an example retrieving a WebRTC promise value using a timeout.

_x000D_
_x000D_
function await_getipv4(timeout = 1000) {_x000D_
    var t1 = new Date();_x000D_
    while(!window.ipv4) {_x000D_
        var stop = new Date() - t1 >= timeout;_x000D_
        if(stop) {_x000D_
            console.error('timeout exceeded for await_getipv4.');_x000D_
            return false;_x000D_
        }_x000D_
    }_x000D_
    return window.ipv4;_x000D_
}_x000D_
_x000D_
function async_getipv4() {_x000D_
    var ipv4 = null;_x000D_
    var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})_x000D_
    findIP.then(ip => window.ipv4 = ip);_x000D_
    return await_getipv4();_x000D_
};
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to promise

Axios handling errors typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here Syntax for async arrow function Angular 2: How to call a function after get a response from subscribe http.post How to use fetch in typescript Returning Promises from Vuex actions Use async await with Array.map Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai using setTimeout on promise chain Why is my asynchronous function returning Promise { <pending> } instead of a value?

Examples related to angular-promise

Angular 1.6.0: "Possibly unhandled rejection" error What is the difference between Promises and Observables? How to access the value of a promise? How to return a resolved promise from an AngularJS Service using $q? Wait for all promises to resolve Error handling in AngularJS http get then construct AngularJS : Initialize service with asynchronous data How to cancel an $http request in AngularJS?