简体   繁体   English

API中的变量更改时如何调用函数

[英]How to call a function when a variable changes in an API

I am calling an API and updating the objects variables on interval. 我正在调用API并按间隔更新对象变量。 Within the updateAPI function I wanna check if the variable increases and if it does I wanna call a function. 在updateAPI函数中,我要检查变量是否增加以及是否要调用函数。

I have tried setters and getters, storage and other methods. 我已经尝试了setter和getter,存储和其他方法。 Also played around a lot with different variants of current code but I can't understand the other solutions. 在当前代码的不同变体中也发挥了很多作用,但我无法理解其他解决方案。

function updateAPI() {
  var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
          callback(null, xhr.response);
      } else {
          callback(status);
      }
    };
    xhr.send();
  };
  getJSON('api.example.com',  function(err, response) {
    if (err != null) {
      console.error(err);
    } else {
      let data = response.data
      var followers = data.followers_count
      var old = followers;

      function check() {
        if (old > followers) {
          console.log('changed');
          var old = followers;
        }
        if (old < followers) { 
          console.log('not changed'); 
          var old = followers; 
        }
      }
      setInterval(check, 5000);

    }
  });
}
updateAPI();
setInterval(() => { updateAPI() }, 10000);

The current code does not log any changes happening to the API. 当前代码不会记录API发生的任何更改。 But I can console.log('followers') and see the value changing. 但是我可以使用console.log('followers')来查看值的变化。

Just some minor things to start: 只是一些小事情要开始:

Move getJSON outside and above of updateAPI . getJSON移动到updateAPI外部和上方。 Right now every time it gets called, it is creating a new function which isn't needed. 现在,每次调用它时,它都会创建一个不需要的新函数。 Also you can probably just replace it with the fetch api . 您也可以只将其替换为fetch api You can also abstract the check function and allow it to accept an argument (or two) and tell you if you should update. 您还可以抽象check函数,并使其接受一个(或两个)参数,并告诉您是否应更新。

Secondly have your tried debugging this some how? 其次,您是否尝试过调试呢? Either using console.log statements or the Chrome debugger? 使用console.log语句还是Chrome调试器? The problem lies in this code: 问题出在以下代码中:

var followers = data.followers_count
var old = followers;

followers and old will always be equal. followersold 永远平等。 You're re-assigning them every time you call your function. 每次调用函数时都要重新分配它们。 That is why you're seeing it change, but never seeing it log anything. 这就是为什么您看到它发生变化,但从未看到它记录任何内容的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM