0

I need get argument "i" from callback function and move it to "obj". I read many same topics but I still dont understand how it work. Please someone help.

function getData(index,callback) 
    {
        var openReq = indexedDB.open("catalogs");
        openReq.onsuccess = function() 
        {


            var db = openReq.result;
            var transaction = db.transaction(['plants'], "readwrite");
            var objectStore = transaction.objectStore("plants");
            var objectStoreRequest = objectStore.get(index);
            var store=null;  
              objectStoreRequest.onsuccess =function(event)
              {
              store =objectStoreRequest.result;

              //console.log(store);
              return store;
              }
              transaction.oncomplete = function(event)
              {
                db.close();
                if(callback)
                    callback(store);
              }
        }
    }

...SOME CODE.....

    for (var i = 101; i < 272; i++){
        var obj= new Object();
        getData(''+i,function (i){document.obj=i;});
        console.log(obj);
        }
l1s4un
  • 5
  • 6
  • You can't. That's *why* you have a callback for asynchronous operations. The callback is supposed to do whatever needs to be done with the results. You could restructure the code to use promises, so that it would at least read more like synchronous code. – nnnnnn May 19 '17 at 04:00

1 Answers1

0

... which value do you want, i from the for loop or i from the callback? They're 2 different values.

Callback Result

(the one I think you want)

for (var i = 101; i < 272; i++){
    var obj = {}; // same as `new Object()`
    getData( i.toString(), function (result){
        obj.yourPropertyNameHere = result;
        console.log(obj);
    });
}

Iterator Index

for (var i = 101; i < 272; i++){
    // we have to store a copy of the variable `i` in the closure
    // of a function, otherwise all of the callbacks will reference
    // the final value of `i` from the loop
    (function(i_copy){

        var obj = {}; // same as `new Object()`
        getData( i_copy.toString(), function (result){
            obj.yourPropertyNameHere = i_copy;
            console.log(obj);
        });

    })(i);
}
THEtheChad
  • 2,372
  • 1
  • 16
  • 20
  • Either way, the callback won't be executed until after the `console.log()` statement, because `getData()` is doing asynchronous stuff. – nnnnnn May 19 '17 at 04:03
  • @nnnnnn Good point. I wasn't even paying attention to the callback. There's so many problems with this code. – THEtheChad May 19 '17 at 04:05
  • @nnnnnn callback work normal. I can show my data to console like this `getData(''+i,function (i){document.obj=console.log(i);});` – l1s4un May 19 '17 at 04:13
  • @LischukAndry: ... `console.log(i)` returns `undefined`. You're storing the value of `undefined` in a property called `obj` on the `document` object. – THEtheChad May 22 '17 at 06:38