bind variable to .await()
timmy-guyon opened this issue · 2 comments
Is it possible to pass a variable to .await()?
It doesn't look like .await() supports .bind(). Forgive my ignorance, I'm new to both d3 and asynchronous programming.
Here's my code for context
`function update_left_chart_v2() {
console.log("\n update left chart called v2!");
var leftSection = $("#dashboard > div:nth-child(2) > div.left-section").width();
for (svgSection in indexSVGSections) {
//define variables for section
sectionNumber = indexSVGSections[svgSection]["sectionNumber"];
sectionMetric = indexSVGSections[svgSection]["sectionMetric"];
sectionMetricCode = indexSVGSections[svgSection]["sectionMetricCode"];
sectionIndexes = indexSVGSections[svgSection]["indexes"];
console.log('section number: ' + sectionNumber + ' |section metric: ' + sectionMetric + '|section metric code: ' + sectionMetricCode + '\n');
//add each d3.csv call to a queue, process when all completed
var q = d3.queue();
for (var index in sectionIndexes) {
index = sectionIndexes[index];
var fileName = index["fileName"];
var indexActive = index["active"];
var className = index["className"];
if (indexActive) {
console.log(index);
var filePath = directory + "out-" + fileName + "-" + sectionMetricCode + ".csv";
console.log(filePath);
q.defer(d3.csv, filePath);
} else {
q.defer(nullIndex);
}
}
function nullIndex(callback) {
callback(null);
}
q.await(function(error, index1Data, index2Data, index3Data) {
//THIS IS WHERE I NEED TO USE THE VARIABLE "sectionNumber" which changes with each iteration of for loop
//
console.log(sectionNumber);
if (error) {
console.log(error);
} else {
if(sectionCounter > 5){
sectionCounter = 1;
}
console.log("await finished");
console.log(" index 1 data");
console.log(index1Data);
// console.log("index 2 data");
// console.log(index2Data);
// console.log("\n");
// console.log("index 3 data");
// console.log(index3Data);
// console.log("\n");
var dataAssigned = false;
index1Data.forEach(function(rowData, i) {
rowDate = rowData.date;
rowValue = rowData.value;
if (rowDate.substr(0, 4) == sliderYear && !dataAssigned) {
console.log("date: ", rowDate, " | row value: ", rowValue, " | i: ", i);
dataAssigned = true;
// indexSVGSections[section1]
}
});
console.log("\n");
}
});
}
}`
when "console.log(sectionNumber)" is called, it reads and calls it as its last assigned value, as it's being called asynchronusly. I need to bind each iteration of sectionNumber to .await() so it can read it as it changes.
Just a suggestion - you could wrap d3.csv in a custom function and then pass sectionNumber to this function.
The q.defer call might look like this -
q.defer(myCustomCsvLoader, filePath, sectionNumber)