0

I have this code:

rtclient.listFiles = function(callback) {
  gapi.client.load('drive', 'v2', function() {
    gapi.client.drive.files.list({
      'maxResults': 20
    }).execute(callback);
  });
}

which I try to assign to an array using this code:

var arrayStore;

rtclient.listFiles(function(x) {
              for(var i in x.items) {
              arrayStore.push(x.items[i].id);
            }})

However, the array arrayStore is not storing anything. This is using the Google Drive API and I am trying to access some file IDs to iterate over. Can anyone help?

LeDoc
  • 935
  • 2
  • 12
  • 24

1 Answers1

1

the point is you should have a error like:

TypeError: Cannot call method 'push' of undefined

because you haven't defined it as an array, the other point is don't use for(...in) for arrays, you can find reasons about that in this post:

Why is using “for…in” with array iteration such a bad idea?

var arrayStore = [];
rtclient.listFiles(function(x) {
    for(var i = 0; i < x.items.length; i++) {
        arrayStore.push(x.items[i].id);
    }
});

The other important point as @toothbrush has commented is, since the Google Drive API is asynchronous, you can't access the contents of arrayStore immediately, in other word to continue your scenario you should do something like this:

var arrayStore = [];
rtclient.listFiles(function(x) {
    for(var i = 0; i < x.items.length; i++) {
        arrayStore.push(x.items[i].id);
    }
    nextStep();
});
function nextStep(){
    //here you would have access to arrayStore
    console.log(arrayStore);
}
Community
  • 1
  • 1
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
  • Also, you should note that since the Google Drive API is asynchronous, you can't access the contents of `arrayStore` immediately. – Toothbrush Feb 15 '14 at 20:44
  • That worked! What do you mean by the Google Drive API being asynchronous and how does that relate to my example? – LeDoc Feb 16 '14 at 11:30
  • @user2784840: I have considered it in my answer, he means you can't have access right after `listFiles` is called, you should call a function like `nextStep()` to continue your scenario. – Mehran Hatami Feb 16 '14 at 11:57