嗨,Javascript/Node.js-Developer,
我遇到了一个很好的老问题,异步Javascript只提供数组的最后一项(如HERE和HERE所示)。不幸的是,所提供的解决方案都不适合我。
我正在运行Node版本0.10.25。我编写了一个最小的(非)工作示例:
var neededTables = [{
name: "ipfix_exporters",
},{
name: "ipfix_messages",
}];
var params = {};
console.log('[1] Connected to hana-database');
neededTables.forEach(function(table) {
params.table = table;
console.log("Checking table: " + params.table.name);
checkForTable.bind(null, params)();
});
function checkForTable(thoseParams) {
setTimeout(
(function(myParams) { return function(err, rows) {
if(err) {
console.log(err);
return;
}
console.log("Table '"+myParams.table.name+"' does exist!");
}})(thoseParams), 1000);
}预期的输出:
[1] Connected to hana-database
Checking table: ipfix_exporters
Checking table: ipfix_messages
Table 'ipfix_exporters' does exist!
Table 'ipfix_messages' does exist!实作输出:
[1] Connected to hana-database
Checking table: ipfix_exporters
Checking table: ipfix_messages
Table 'ipfix_messages' does exist!
Table 'ipfix_messages' does exist!我完全不知所措。希望有人
发布于 2014-01-29 10:01:55
对于每个函数调用,您都重用相同的params对象。所以他们都看到了它的最新更新。
简单修复-为每个函数调用创建一个新的params对象
neededTables.forEach(function(table) {
params = {};
params.table = table;
console.log("Checking table: " + params.table.name);
checkForTable.bind(null, params)();
});更好的是,由于您没有在params作用域之外使用forEach,请将其移到其中。
neededTables.forEach(function(table) {
var params = { table: table };
console.log("Checking table: " + params.table.name);
checkForTable.bind(null, params)();
});然后,由于您只设置了一个属性的params,只需直接使用它。
neededTables.forEach(function(table) {
console.log("Checking table: " + table.name);
checkForTable.bind(null, table)();
});发布于 2014-01-29 09:56:45
在此代码中:
neededTables.forEach(function(table) {
params.table = table;
console.log("Checking table: " + params.table.name);
checkForTable.bind(null, params)();
});当您设置params.table时,foreach函数的每一次迭代都是用下一个表更新params.table。
当您以1000 is的超时调用下面的函数时,foreach循环将立即继续,因为超时是异步的,将params.table设置为下一个表。这将一直持续到foreach循环结束,其中params.table被设置为数组中的最后一个值。
因此,当所有超时的回调发生时,foreach函数将已经完成,所有回调都将打印相同的值。
发布于 2014-01-29 10:00:18
将params变量引入您的forEach范围内:
console.log('[1] Connected to hana-database');
neededTables.forEach(function(table) {
var params = {};
params.table = table;
console.log("Checking table: " + params.table.name);
checkForTable.bind(null, params)();
});https://stackoverflow.com/questions/21427339
复制相似问题