I tried to write a small code to download many files (in this example: one .json and one .svg file) and I stumbled into some code I don't understand. I promise, next time I use a Promise, nonetheless, here is the code :
var path_name = "some/path/to/go";
var item_name = "some_item_to_get";
var load_lst = [
[server_get_json, "/cdn/json/?m={0}&q={1}".format(path_name, item_name), "m_json", false],
[server_get_svg, "/cdn/svg/?m={0}&q={1}".format(path_name, item_name), "m_svg", false],
];
var bucket = new Object;
Then I use the following snippet to launch all the downloads, store the result in the bucket and set a flag to true
.
for (let i=0 ; i<load_lst.length ; i++) {
load_lst[i][0](load_lst[i][1], (obj) => {
console.log(i, load_lst[i][0], load_lst[i][1], load_lst[i][2]);
bucket[load_lst[i][2]] = obj;
load_lst[i][3] = true;
});
}
which logs
1 function server_get_svg() /cdn/svg/?m=some/path/to/go&q=some_item_to_get m_svg
0 function server_get_json() /csn/json/?m=some/path/to/go&q=some_item_to_get m_json
which is perfectly fine. But the following one does not work at all... the same function is called twice and, generally speaking, my vars are all mixed up.
for (let i=0 ; i<load_lst.length ; i++) {
var [func, url, name, status] = load_lst[i];
func(url, (obj) => {
console.log(func, url, name);
bucket[name] = obj;
load_lst[i][3] = true;
console.log(func, url, name, load_lst[0][3], load_lst[1][3]);
});
}
which logs :
function server_get_svg() /cdn/svg/?m=some/path/to/go&q=some_item_to_get m_svg false true
function server_get_svg() /cdn/svg/?m=some/path/to/go&q=some_item_to_get m_svg true true
I don't understand why the local variable i
is correctly known in the following anonymous callback, and why load_lst[i]
works perfectly fine, but func
, url
, name
, status
do not.
If fact, if I may understand why the second doesn't work, I don't understand why the first one does :)