如果断点触发其分配,则不会触发IndexedDB回调

时间:2017-03-10 12:23:23

标签: javascript indexeddb event-loop

检查此代码段:

function connect() {
    var request = window.indexedDB.open('test', 1);

    request.onerror = function(event) {
      console.log('error');
    };

    request.onupgradeneeded = function (event) {
      console.log('upgrade needed');
    };

    request.onsuccess = function(event) {
      console.log('success');
    };
}

connect();

当我在回调分配行(4,8,12)上放置断点并在chrome调试器中运行它时,回调中的代码将永远不会触发。相反,此代码将正常工作:

  function connect2() {
    var IDB = {
      open: function() {
        var req = {};
        setTimeout(() => {
          req.onsuccess();
        }, 0)
        return req;
      }
    }
    var request = IDB.open();

    request.onsuccess = function(event) {
        console.log('onsuccess2');
    };
  }
  connect2();

我是否理解正确,IndexedDB.open和debugger的情况会破坏js事件循环?这可能是什么原因?

2 个答案:

答案 0 :(得分:0)

它为我工作! onsuccess和onupgradeneeded被调用! 见小提琴:



function connect() {
    var request = window.indexedDB.open('test', 1);

    request.onerror = function(event) {
      console.log('error');
    };

    request.onupgradeneeded = function (event) {
      console.log('upgrade needed');
    };

    request.onsuccess = function(event) {
      console.log('success');
    };
}

connect();




答案 1 :(得分:0)

如果您想使用更多模块化:



var APP = APP || {};

APP.Database = (function(){
	
  return {
      request : null,

      init : function()
      {
          this.connect();
          this.request.onerror = this.logError;
          this.request.onupgradeneeded = this.onUpgradedNeeded;
          this.request.onsuccess = this.onSuccessCallback;
      },
      connect : function()
      {
        this.request = window.indexedDB.open('test', 1);
      },
      onSuccessCallback : function(evt)
      {
        console.log('Successfully conneted!');
      },
      logError : function(evt)
      {
        console.log('error');
      },
      onUpgradedNeeded : function(evt)
      {
         console.log('upgrade needed');
      }
    };  
})();


APP.Database.init();