0

I would like to pass extra value to promise .done. The problem is that console.log(dataToDownload) always prints "b".

var downloadData = {
    'a': 'http://www.aaa.aa?callback=?',
    'b': 'http://www.bbb.bb?callback=?',
}

var promises = [];

for (dataToDownload in downloadData){

    promises.push($.get(downloadData[dataToDownload], {}, null, 'jsonp')
        .done(function(results){

            console.log(dataToDownload)
            console.log(results);

        }))
}

$.when.apply($, promises).done(function(){

    console.log('Downloaded!')

})

I've tried IIFE:

 .done( (function(id){

            console.log(id)
            console.log(results);

        })(dataToDownload); ))

But I don't know how to pass 'results' to IIFE.

What would be the best solution to be able to access both: results and dataToDownload inside .done?

LAdas
  • 439
  • 1
  • 5
  • 13
  • You can already access `dataToDownload`, it's in its lexical scope... – elclanrs Mar 22 '16 at 15:45
  • Your issue may be this one http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – elclanrs Mar 22 '16 at 15:46
  • @elclanrs: `console.log(dataToDownload)` in the first example prints 'b' twice – LAdas Mar 22 '16 at 15:50
  • Yeah, this seems to be a duplicate of the question I linked above. – elclanrs Mar 22 '16 at 15:52
  • @elclanrs: yes, problem is somehow related, symptoms are the same, but how to solve it in my case (JQuery promise + `.done`)? – LAdas Mar 22 '16 at 16:15
  • The issue is the same, you gotta wrap your code within the loop in an IIFE, or easier, just use `Object.keys(downloadData).forEach(function(dataToDownload){...`. – elclanrs Mar 22 '16 at 16:18
  • Could you provide full answer, so it will be simpler to test it – LAdas Mar 22 '16 at 16:30

1 Answers1

0

console.log(downloadData[dataToDownload])

Hari Lubovac
  • 622
  • 4
  • 14