索引db获取所有值,变量不分配值 - 异步错误

时间:2018-06-12 11:50:32

标签: javascript asynchronous callback indexeddb

我正在尝试使用以下函数从indexeddb获取所有数据。

var databasehandler={}
 databaseHandler.getAllContacts=function(callback){
var resultarray = new Array;
var objectStore = db.transaction(databaseHandler.TABLE_CONTACTS).objectStore(databaseHandler.TABLE_CONTACTS);
          var keyRange = IDBKeyRange.lowerBound(0);
         objectStore.openCursor(keyRange).onsuccess = function(event) {
           var cursor = event.target.result;
           //console.log("valueee:"+event.target.result);

           if (cursor) {
               resultarray.push(cursor.value);
              //console.log("Name for id " + cursor.key + " is " + cursor.value.name + ",  Age: " + cursor.value.age + ", Email: " + cursor.value.email);
              cursor.continue();
           } else {
              console.log("No more entries!");
           }
        };
    callback(resultarray);
}

并使用

调用该函数
var allcontacts;
        databaseHandler.getAllContacts( function(data){allcontacts=data});
        if(allcontacts.length>0){
            console.log('higher' +allcontacts[0]);
            }else{console.log('lower');
                }

所以我需要获取所有数据的长度。如果3个数据在那里它应该打印更高和第一个数据..但我得到

    TypeError: allcontacts is undefined[Learn More]

我知道.onsuccess是一个异步函数,这就是我尝试回调方法的原因。甚至我尝试使用“$ .Deferred()”这样:

databaseHandler.getAllContacts=function(){
var resultarray = new Array;
var defer = $.Deferred();
var objectStore = db.transaction(databaseHandler.TABLE_CONTACTS).objectStore(databaseHandler.TABLE_CONTACTS);
         var keyRange = IDBKeyRange.lowerBound(0);
         objectStore.openCursor(keyRange).onsuccess = function(event) {

           var cursor = event.target.result;
           //console.log("valueee:"+event.target.result);

          if(!!cursor == false) {
     // Send the information back to our specified function
    // Callback(resultarray);
    defer.resolve(resultarray);
     return
  }
  resultarray.push(cursor.value);

  cursor.continue();
        };

}

但那个也没用。请为此提供解决方案..回调无效。请让我知道我错过了什么?我也使用了以下代码..相应地调用了函数。

databaseHandler.getAllContacts=function(Callback){
var resultarray = new Array;
var defer = $.Deferred();
var objectStore = db.transaction(databaseHandler.TABLE_CONTACTS).objectStore(databaseHandler.TABLE_CONTACTS);
         var keyRange = IDBKeyRange.lowerBound(0);
         objectStore.openCursor(keyRange).onsuccess = function(event) {

           var cursor = event.target.result;
           //console.log("valueee:"+event.target.result);

          if(!!cursor == false) {
     // Send the information back to our specified function
     Callback(resultarray);

     return
  }
  resultarray.push(cursor.value);

  cursor.continue();
        };

}

0 个答案:

没有答案