Request-Promise: do promise cache the result

五迷三道 提交于 2021-02-16 20:04:30

问题


I'm using Request-Promise (See code below).

Question: If I cache a promise, do it cache the result or each time ask a new one?

Example:

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: 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13',
        method: 'POST',
        body: querystring.stringify({
            'client_id': 'Subtitles',
            'client_secret': 'Xv.............................s=',
            'scope': 'http://api.microsofttranslator.com',
            'grant_type': 'client_credentials'
        })
    };
    return rp(requestOpts);
}

回答1:


If I cache a promise, do it cache the result

A promise can only have a single result (in case it doesn't get rejected). It therefore can also be only resolved only once - and must not change its state thereafter.

In fact, the promise spec states

      1. When fulfilled, a promise:
        • must not transition to any other state.
        • must have a value, which must not change.

or each time ask a new one?

No. getTokenPromise() is the call that asks for the token, and it is executed only once. cachedPromise only represents the result, not an action. The action itself would have been executed even if you didn't add a callback via .then().



来源:https://stackoverflow.com/questions/26022458/request-promise-do-promise-cache-the-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!