将参数传递给q.defer(d3.csv)
问题描述:
如何在d3中将参数传递给q.defer? 我需要通过一个索引(文件名 - d)位置:将参数传递给q.defer(d3.csv)
var data = [1,3,5,6,7];
var q = d3.queue();
data.map(function(d){
q.defer(d3.csv,'https://***/'+d+'.csv', d); //something like pass d
})
q.awaitAll(function(error, result, d) {//and get the d here according to results
if (error) throw error;
//how to get the d value here?
});
有没有办法让awaitAll内d | 谢谢。
答
只有通过父范围:
var myd = data.map(function(d){
q.defer(d3.csv,'https://***/'+d+'.csv', d);
return d
})
q.awaitAll(function(error, result, d) {
if (error) throw error;
//how to get the d value here?
console.log(myd) // myd contains all the d from your map.
});
但是由于是在data.map()
呼叫时,您已经使用过所有的data
(data
势必d
映射器函数内):
q.awaitAll(function(error, result, d) {
if (error) throw error;
//how to get the d value here?
console.log(data) // this is the same `data` from the `data.map()`
});
编辑:原来的问题不清楚。该OP显然想重新映射结果反馈到d
值:
q.awaitAll(function(error, result) {
if (error) throw error;
//how to get the d value here?
result.map(function(res, idx) {
console.log("original d:" + data[idx].toString())
}
});
awaitAll文档:https://github.com/d3/d3-queue#queue_awaitAll
一些额外的阅读材料:
https://scotch.io/tutorials/understanding-scope-in-javascript
https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/
肯定的,但是根据d值我需要结果。据我所知,“结果”总是随机的,因为它是一个线程,或者我错了吗? – SERG
'results'是你制作的所有延期数组。 'result [0]'对应于'data [0]'对应'd == 1'。 – cowbert
谢谢,我认为,因为它是异步的,那么结果顺序将是随机的 – SERG