from MySQL to IndexedDB

本秂侑毒 提交于 2019-12-04 18:11:52

Well, for starters, you are mixing two async systems together (ajax and indexedDB), which will not always work. In order to guarantee that it will always work, you will need to rewrite the code so that you first fetch the json data, wait for it to complete, and then connect to the database, start a transaction, and execute put requests.

If you are familiar with promises, and you are also familiar with the new async functionality, and const/let, maybe something like this:

// Asynchronously open a connection to indexedDB
function openIndexedDBDatabase() {
 return new Promise(function(resolve, reject) {
   const request = indexedDB.open('dbname', dbversionnumber);
   request.onsuccess = () => resolve(request.result);
   request.onerror() = () => reject(request.error);
 });
}

// Asynchronously fetch some json data
function getJsonAsync(url) {
  return new Promise(function(resolve, reject) {
    $.getJSON(url, resolve);
  });
}

// Asynchronously store the data in indexedDB
function storeTheDataInIndexedDb(db, data) {
  return new Promise(function(resolve, reject) {
     const transaction = db.transaction('storename', 'readwrite');
     transaction.oncomplete = () => resolve();
     transaction.onerror = () => reject(transaction.error);
     const store = transaction.objectStore('storename');
     for(let obj of data) {
       store.put(obj);
     }
  });
}

// Asynchronously do all the things together
async function doStuff() {
   if(!navigator.onLine) {
      const data = await getJsonAsync('./php/database.php');
      const db = await openIndexedDBDatabase();
      await storeTheDataInIndexedDb(db, data);
      db.close();
   } else {
      openPHPdatabase();
   }
}

doStuff();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!