how to round-trip data on multiple OData.read calls?

Dec 9, 2013 at 3:59 PM
I have a loop, and I'm calling "OData.read" within it. The maximum it will loop through is 6 times, but it may loop less, dependent on the situation.

My code looks like this:
for (var i = 0; i < someArray.length; i++) {
   var collection = someArray[i];
                
   OData.read({requestUri: collection.href, user: "user", password:"password"},
      function(data, response) {
         var dataAsStr = JSON.stringify(data.results);
         localStorage.setItem(collection.title, dataAsStr);
      });
   }
            
So, I'm making a call, getting data back, and writing it out to localStorage. but I want to use the title of each collection, for the key used in localStorage. Problem is, the callback is asynchronous, so collection.title isn't valid when I get here. What I'd like to do is pass in a value into my read call, that would get returned to me in the success function. Can this be done?
Aug 9, 2015 at 10:40 PM
Edited Aug 9, 2015 at 10:41 PM
I'm working on a similar problem. My solution is to wrap the OData.read(...) in its own function. Here's an example. In it, I use the productIndex in the callback that processes the data. In your case, you would replace the productIndex with the collection title.

I've been working with datajs for just about one week now. Please tell me if you already found a better solution to this problem. :-)
Dec 30, 2015 at 6:25 PM
Just wrap the OData.read({ ... }); inside an IFEE and pass in the collection as a parameter.
for (var i = 0; i < someArray.length; i++) {
   var collection = someArray[i];
                
   (function(c) {
     OData.read({requestUri: c.href, user: "user", password:"password"},
        function(data, response) {
           var dataAsStr = JSON.stringify(data.results);
           localStorage.setItem(c.title, dataAsStr);
        });
    }(collection));
}