在 IndexedDb 中的游标外访问游标中设置的变量

Accessing a variable set in cursor outside the cursor in IndexedDb

我想打印我在光标内部设置的变量 "set" 的值,在我的光标对象之外。

      request.onsuccess = function(e){
      var set = 0;
      var transaction = db.transaction(['List'], "readonly");
      var objectStore = transaction.objectStore('List');

      objectStore.openCursor().onsuccess = function(event) {
        var cursor = event.target.result;
        if(cursor) {
        // console.log(cursor.value.Name);
        if (cursor.value.Name == $('#card').val())
        {
          console.log("aisa kabhi hoga hi nahi");
          set = 1;
        }

          cursor.continue();
        } 
        else 
        {
          console.log('Entries all displayed.');
          if (set == 0)
          {
             set= ippp();
             console.log(set);

          }
        }
      };
      console.log(set);
      }

当我在光标内打印我的设置变量时 "right data is printed"。

但是当我尝试在光标外打印变量 "set" 的数据时,我最初声明的值被打印出来了。 "How is it possible as I am resetting the value of variable in my cursor"

我的问题是如何在游标内部、游标对象外部访问我设置为变量 "set" 的值。

在使用indexedDB之前,您需要了解异步编程。真正的答案是去学习这个。

但是,作为快速回答,您可以使用回调函数。

function outerFunction(myCallbackFunction) {
  // do stuff
  request.onsuccess = function(event) {
    var cursor = event.target.value;

    var value = cursor.value;

    // Here is the whole trick to getting the value out. Pass the value to the 
    // callback function.
    myCallbackFunction(value);
  };
}

// Then to call it, you do something like this, where 'oncompleted' 
// is the name of the callback function

outerFunction(function oncompleted(value) {
  console.log('The value is', value);
});