Request-Promise:承诺对结果进行缓存 [英] Request-Promise: do promise cache the result

查看:31
本文介绍了Request-Promise:承诺对结果进行缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用请求-承诺(请参见下面的代码).

问题: 如果我缓存了一个诺言,是缓存结果还是每次都问一个新的诺言?

示例:

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

getTokenPromise()函数:

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);
}

推荐答案

如果我缓存了诺言,就缓存结果

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.

实际上,承诺规范指出

  1. 兑现承诺时:
    • 不得过渡到其他任何状态.
    • 必须具有一个值,该值不得更改.

还是每次都问一个新的?

or each time ask a new one?

不. getTokenPromise()是请求令牌的调用,并且仅执行一次. cachedPromise 表示结果,而不是操作.即使您没有通过 .then()添加回调,该动作本身也会被执行.

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().

这篇关于Request-Promise:承诺对结果进行缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆