0

I need to combine two Chrome APIs in loop and after the loop is finished, save array to storage.
This is what I have

chrome.downloads.search({}, function (DownloadItem) {
    for (var i=0; i<DownloadItem.length; i++) {
        var itemID = DownloadItem[i].id;
        chrome.downloads.getFileIcon(itemID, function(iconURL) {
            DL_icons[itemID] = iconURL;
        });     
    }
    console.log(DL_icons);
});  

result of search is DownloadItem array of objects. I need to loop through it, get ID's, and for every ID I need to pass it into call of chrome.downloads.getFileIcon.
Result of that getFileIcon method is iconURL which I need to push into new array on ID index (I could store it into new object with according ID and then push it into an array, doesn't matter in this case).

After everything is done, I need to store it to local storage (or console.log...). As it is now, I'm getting the same ID and iconURL for every array element.
Basically, I need to make a proper closure of inner API, and just can't make it right. Can someone pls help with it?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Wolf War
  • 1,503
  • 1
  • 15
  • 28
  • 1
    Looks like a mix of the [everyday AJAX problem](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call), and the [infamous loop closure issue](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – elclanrs Aug 23 '14 at 21:41
  • should I split it into outer function? would that help? – Wolf War Aug 23 '14 at 21:43
  • btw. I can't use IIFE, because in that case, I can't get IDs.... or can I? – Wolf War Aug 23 '14 at 21:45
  • @elclanrs I stand corrected :) IIEF is solution, thank you – Wolf War Aug 23 '14 at 21:51

1 Answers1

1

If anyone stumble on simmmilar problem, this is how I solve it, thanx to @elclanrs suggestion

it is from this answer

chrome.downloads.search({}, function (DownloadItem) {
    for (var i=0; i<DownloadItem.length; i++) {
        var itemID = DownloadItem[i].id;
        (function(index) {
            chrome.downloads.getFileIcon(index, function(iconURL) {
                DL_icons[index] = iconURL;
                console.log(DL_icons);
            });
        })(itemID);         
    }
});

instead of passing the loop index, I passed my ID variable... job's done

Community
  • 1
  • 1
Wolf War
  • 1,503
  • 1
  • 15
  • 28