问题
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
- 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