gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:38:43 26 4
gpt4 key购买 nike

我的问题是,我绑定(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com