在Javascript中设置promise链中变量的值

时间:2018-02-27 15:21:40

标签: javascript

在我的Web应用程序中,有几个组件需要访问相同的数据(在JSON中)。为了避免进行不必要的REST调用,我创建了一个模块,该模块应该生成一个获取请求并将结果存储在一个变量中。在后续请求中......如果模块中有数据,则会直接返回(因此只需要一个网络请求)。

例如:

some_dom_element.onclick = function(){ //Some html element is clicked and we need the data

   data_module.get_json().then(function(json){
      console.log(json); //However this never gets called 
  });

}

在模块之外,我将尝试访问这样的数据:

class ClassB
{
public:
    void Foo2(ClassA* a)
    {
        // Do stuff with "a" here
    }
}; // <- semicolon

它不起作用。即使data_module的get_json函数返回Promise,也不会在data_module之外调用.then方法。我想知道是否有人能解释为什么会这样? (或者提供如何修改解决方案以实现存储获取请求的json结果的目标的一般方向。)

提前致谢!

2 个答案:

答案 0 :(得分:2)

您需要返回fetch

var data_module = (function() {
  var data; //Module stores the json data in a variable

  return { //Returns an object that contains a public method accessible to external functions
    get_json: function() {
      if (data) { //If data already exists, then return a Promise object that immediately resolves with data
        console.log("** From CACHE **")
        return Promise.resolve(data);
      } else { //Else if data does not exist, make fetch request 
      // returning the fetch 
     return fetch('https://jsonplaceholder.typicode.com/posts/1', {
            credentials: 'include'
          })
          .then(function(response) {
            if (!response.ok) {
              throw new Error(response.statusText);
            }
            return response.json(); //Returns json of response
          })
          .then(function(json) {
            data = json;
            return Promise.resolve(data) //Returns a Promise that resolves with data

          });


      }
    } //Public method that is supposed to provide access to data

  }
}()); //Module will automatically execute
//Outside of the module, I will try to access data like so:
var some_dom_element = document.getElementById("testBt")
some_dom_element.onclick = function() { //Some html element is clicked and we need the data

  data_module.get_json().then(function(json) {
    console.log(json); //However this never gets called 
  });

}
<button id="testBt">Test</button>

答案 1 :(得分:1)

通过存储response.json()返回的承诺并且只返回它而不是存储文本并在每次从缓存中获取它时生成新的Promise,实际上可以缩短代码。

let data_module = (function() {
  let data;

  return {
    get_json: () => {
      if (!data) {
        data = fetch('https://jsonplaceholder.typicode.com/posts/1', {
          credentials: 'include'
        })
        .then(response => {
          if (!response.ok) {
            // clear data so next time it tries to contact the server again
            data = undefined;
            throw new Error(`${response.status}: ${response.statusText}`);
          } else {
            // return the promise that .json() returns so it is stored
            // in data
            return response.json();
          }
        });
      }
      
      return data;
    }
  };
}());


data_module.get_json().then(data => {
  console.log(data);
});
data_module.get_json().then(data => {
  console.log(data);
});

我使用letarrow functions =>,因为任何支持fetch的浏览器也支持这些。