0

Before you all baulk at nesting a method within a loop, this is an example where I truly see no other way. Though, I will entertain other suggestions.

Anyways, I'm using the Dropbox.js SDK for their API. I am looking in a directory for files given based on extension given the following list and path:

FILE_EXTENSIONS = [".py",".js",".cpp",".html",".h"];
PATH = "/Developer";

My code is as follows:

var counts = [];

look_for_files(PATH, FILE_EXTENSIONS);


function look_for_files(directory_path, file_extensions){
    for (var i = 0; i < file_extensions.length; i++){
        current_file = file_extensions[i];

        client.search(PATH, current_file, function(error, count){
            if(error){ 
                return showError(error);
            }
            console.log(current_file); // Problem is here.
            console.log(count.length);
            counts.push(count.length);
        });
    }
};

Now, when I log the (count.length) I get the following output:

.h
88
.h
607
.h
665
.h
180
.h
410 

The numbers are changing, but the current_file is not, even though it's being passed into the method. I have no idea why. This is one of my first experiences programming in javascript (I come from an OOP background), but I am lost. Could someone please help explain?

Thanks

carbon_ghost
  • 1,114
  • 5
  • 18
  • 40
  • @elclanrs If this a duplicate question, I would love to see where it exists so I can stop stumbling with this problem. – carbon_ghost Aug 23 '14 at 00:05
  • 1
    The duplicate is linked above in the question. But there are others http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue – elclanrs Aug 23 '14 at 00:07

1 Answers1

0

Since you are making an asynchronous request, there is a time delay. So, by the time your callback method executes, the for loop has already executed through out, and at this point when you are logging the current_file ( console.log(current_file); ), the index is pointing to the last element in the array.

If you want to log the name of all the files it is processing, move that log statement outside the callback method like this -

function look_for_files(directory_path, file_extensions){
    for (var i = 0; i < file_extensions.length; i++){
        current_file = file_extensions[i];
        console.log(current_file); // This wont be a problem any more

        client.search(PATH, current_file, function(error, count){
            if(error){ 
                return showError(error);
            }

            console.log(count.length);
            counts.push(count.length);
        });
    }
    };

Now, this should be the result:

// This is when inside the loop
.py
.js
.cpp
.html
.h

// this is the callback
88
607
665
180
410 
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Cute_Ninja
  • 4,742
  • 4
  • 39
  • 63