DEV Community

jswalker.in
jswalker.in

Posted on

Which strategy do you prefer for indexedDB?

/idb_object/
var idb_db = window.indexedDB.open("test_db",1);

/*First Approach (Extreme Fast) */
function push_record(obj){

    var transaction = idb_db.transaction(['test_object_store'], 'readwrite');
    var objectStore = transaction.objectStore('test_object_store');
    var request = objectStore1.put(obj);

       request.onsuccess = function(event) { };
       request.onerror = function(event) {
         /*In Case it fails single transaction there is no much we can do ,because loop is on its way.*/
       };
       transaction.oncomplete = function(event) {
          /*Doesn't care loop already fired the next element*/
       };

};

var i=0,obj=[1....10K],len=obj.length;
for(i=0;i<len;i++){
push_record(obj[i]);
}

/First Approach-End/

/Second Approach/
function push_record(obj,callback){

     var data = obj.data;
     var index = obj.index;
     var len = data.length;

     var transaction = idb_db.transaction(['test_object_store'], 'readwrite');
     var objectStore = transaction.objectStore('test_object_store');
     var request = objectStore.put(data[index]);
     transaction.oncomplete = function(event) {
            index++;
            if(index<len){            
              push_record({index:index,data:data},callback);
            }else{
              callback();
            }
     }; 
     request.onsuccess = function(event) {};
     request.onerror = function(event) {
      console.log("Stop operation because,sequencing matters in this iteration");
     };

};

/Consider obj contain uneven large data like ArrayBuffers/
var i=0,obj=[1....10K],len=obj.length;

push_record({index:0,data:obj},function(){
console.log("Everything is pushed seamlessly");
});
/Second Approach-End/

I prefer Second-Approach,it feel much safer and more controlled execution.

Any other strategies please do share?

Top comments (0)