javascript - Does JS bind grab the state of an obj or keep a reference to the obj? -


my issue array i've bind'ed async function doesn't seem updated on subsequent calls of function though bind'ed array updated inside function.

in function below call queryfordata several times asynchronously. passing in history declared globally. log1 prints out empty array , log2 prints out array retrieved correct data iteration. however, doesn't seem concat array retrieved in other calls.

please help

exports.callquery = function(req, res) {   var http = require('http');   var history = [];    // loop on entries in "stocks" collection   // , call queryfordata   stocks.find(function (err, stocks){     stocks.foreach(function callback(entry){         queryfordata(entry, this.history);         }.bind({history : history})     );   });    // perform http request data , call callback    // function concats 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, append `str`       response.on('data', function (chunk) {         str += chunk;       });        //the whole response has been received, print 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() returns new array. so, you're overwriting reference array new array that's never reachable outside function's scope. happens here:

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

try replacing above line with:

data.foreach(function(item){     this.stockshistorydata.push(item); }, this); 

that way build state of existing array.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -