Promise request: promise cache result

I am using Request-Promise (see code below).

Question: If I hide the promise, do the result caching or ask a new one every time?


var cachedPromise = getTokenPromise();
cachedPromise.then(function(authorizationToken1) {
cachedPromise.then(function(authorizationToken2) {
//QUESTION: Is right that authorizationToken1 equals authorizationToken2


GetTokenPromise () function:

var querystring = require('querystring');
var rp = require('request-promise'); 

 * Returns an authorization token promise
function getTokenPromise() {
    var requestOpts = {
        encoding: 'utf8',
        uri: '',
        method: 'POST',
        body: querystring.stringify({
            'client_id': 'Subtitles',
            'client_secret': 'Xv.............................s=',
            'scope': '',
            'grant_type': 'client_credentials'
    return rp(requestOpts);



source to share

1 answer

If I hide the promise, make the result caching

A promise can only have one result (if it is not rejected). Therefore, it can be resolved only once - and should not change its state after that.

In fact, the spec promise states

      1. When fulfilled, the promise:
        • should not change to another state.
        • should have a value that shouldn't change .

or ask a new one every time?

Not. getTokenPromise()

is a call that asks for a token and is executed only once. cachedPromise

represents only the result, not the action. The action itself would have been executed even if you didn't add a callback via .then()




All Articles