我正在使用 Request-Promise (请参阅下面的代码)。
问题:如果我缓存一个 promise ,它是缓存结果还是每次都询问一个新结果?
示例:
var cachedPromise = getTokenPromise();
cachedPromise.then(function(authorizationToken1) {
//...
});
cachedPromise.then(function(authorizationToken2) {
//...
});
//QUESTION: Is right that authorizationToken1 equals authorizationToken2
getTokenPromise() 函数:
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);
}
最佳答案
If I cache a promise, do it cache the result
一个 promise 只能有一个结果(以防它没有被拒绝)。因此,它也只能被解决一次 - 此后不得更改其状态。
事实上,promise spec州
- 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?
没有。 getTokenPromise()
是请求token的调用,只执行一次。 cachedPromise
仅表示结果,而不是 Action 。即使您没有通过 .then()
添加回调,操作本身也会被执行。
关于javascript - 请求 promise : do promise cache the result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26022458/