0

I'm adding data to an indexeddb object store, and my data is in a json array coming from the server like this:

myArray = [[40,'a'],[11,'b']]

So here's my code, and it's working but I'm worried that I'm using a loop:

db = response.target.result
svcTran = db.transaction(['myData'],'readwrite')
myData = svcTran.objectStore('myData')
for (var i=0;i<myArray.length; i++) {
    result.id = myArray[i][0]
    result.name = myArray[i][1]
    svcAdd = myData.add(result)
    svcAdd.onsuccess = mySuccess
    svcAdd.onerror = myFailure
}

I don't think I should put this inside of a loop. I read early on about using functions inside of loops, like it only executes the last one or something.

Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
  • 2
    Do you have a question? –  Oct 17 '16 at 17:04
  • Maybe I should be using myArray.forEach. [Here's another SO question](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example#answer-750506) – Phillip Senn Oct 17 '16 at 17:06
  • Sounds good. Use that. –  Oct 17 '16 at 17:07
  • I can see potential problems here, but instead of asking a question, you seem to be publicly musing for some reason. This isn't the place to get people to perform general review of your code. You should know that. –  Oct 17 '16 at 17:22
  • Actually no, `for(var i = 0; i < 5; i++) console.log(i);` executes for each value of i. the problem resides when you are defining a function while doing `asynchronous`. This happens because the function closes over the value of `i`. Read more about closures [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). – Noctisdark Oct 17 '16 at 17:36

0 Answers0