javascript - JS bind 是获取 obj 的状态还是保留对 obj 的引用?

标签 javascript arrays html node.js asynchronous

我的问题是,我绑定(bind)到异步函数的数组似乎没有在该函数的后续调用中得到更新,即使绑定(bind)的数组在该函数内更新。

在下面的函数中,我多次异步调用 queryForData。传递全局声明的历史。 LOG1 总是打印出一个空数组,而 LOG2 总是打印出一个为该迭代检索到的正确数据的数组。但是,它似乎没有与其他调用中检索到的数组连接。

请帮忙

exports.callQuery = function(req, res) {
  var http = require('http');
  var history = [];

  // loop over all entries in "Stocks" collection
  // and call queryForData
  Stocks.find(function (err, stocks){
    stocks.forEach(function callback(entry){
        queryForData(entry, this.history);
        }.bind({history : history})
    );
  });

  // perform an HTTP request for data and call the callback 
  // function which concats the data arrays together.
  var queryForData = function(stockData, history) {   
    var options = {
      host: 'query.blah.com',
      path: '/blah'+stockData
    };

    var callback = function(response) {
      var str = '';

      //another chunk of data has been received, so append it to `str`
      response.on('data', function (chunk) {
        str += chunk;
      });

      //the whole response has been received, so we just print it out here
      response.on('end', function () {

        var data = JSON.parse(str);
        console.log("LOG1: ", this.stocksHistoryData);
        this.stocksHistoryData = this.stocksHistoryData.concat(data);
        console.log("LOG2: ", this.stocksHistoryData);

        }.bind({stocksHistoryData : history})
      );
    };
    http.request(options, callback).end();
  };
};

最佳答案

concat()返回一个数组。因此,您正在用一个在该函数范围之外永远无法访问的新数组覆盖对该数组的引用。它发生在这里:

this.stocksHistoryData = this.stocksHistoryData.concat(data);

尝试将上面的行替换为:

data.forEach(function(item){
    this.stocksHistoryData.push(item);
}, this);

这样你总是建立现有数组的状态。

关于javascript - JS bind 是获取 obj 的状态还是保留对 obj 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21491829/

相关文章:

javascript - 每个 : undefined is not a function 中的 getBoundingClientRect

c++ - 对象数组

javascript - 如何为 d3 可折叠树中的节点分配唯一的 id

javascript - 禁用旧按钮上的功能

javascript - 如何在 JavaScript 中将匹配的字符串作为变量运行?

php - 将表单元素分布在不同的网页中,看起来简单但无法修复

jquery - 使用 Jquery 切换 HTML 和 CSS

javascript - 将输入文本限制为仅数字,电话号码的最小长度为 10

javascript - 如何过滤SSE脚本中的重复消息?

python - 值错误 : setting an array element with a sequence