1

I'm writing a script in Noded JS that loop inside an array of urls and download each file.

Here a piece of the code:

for(var i = 0; i < 2; i++) {
    var temp_url = dataElencoFatture[i].url;
    const dl = new DownloaderHelper(dataElencoFatture[i].url, cartella_destinazione_pdf, {override: true});
    dl.on('end', (temp_url) => {
        console.log('Download Completed ' + temp_url);
    })
    dl.on('error', (er, temp_url) => {
        console.log('ERRORE Download' + temp_url);
    })                        
    dl.start();
}

Where dataElencoFatture is an array like this one:

[ { anno: '2019',
    numero: '1',
    url: 'http://example.com/test/sample01.pdf' },
  { anno: '2019',
    numero: '2',
    url: 'http://example.com/test/sample02.pdf' },
  { anno: '2019',
    numero: '3',
    url: 'http://example.com/test/sample03.pdf' } ]

As you can see I tried to pass temp_url to the two functions for events "end" or "error" but it does not work. temp_url result undefined.

Kind regards, Matt

agodoo
  • 409
  • 6
  • 21
  • See the linked question's answers. To do that: 1. Don't put `temp_url` in the parameter list at all. Then your functions will close over it. 2. Use `const` to declare it within the loop body (so that each closure gets its own `temp_url`). (Might as well use `let` for `i` as well, but you don't need to in this case.) So: https://pastebin.com/hSCSDV5p – T.J. Crowder Mar 15 '19 at 09:05

0 Answers0