Progressive web application development --- promise Database (five)

In the previous article, we have implemented the use of local data storage indexedDB implement ajax features, details, please see this article . Now we need to put the above article code uses the promise to reconstruct the structure of the next. Why do we need to use the promise to reconstruct it? We have been in use before the code indexedDB, but in indexedDB, we rely heavily on the code correction, if our code more and more, we need it more and more nested callbacks, which for the latter part of code maintenance Not very good.

For example, we can look at the code before we are as follows:

// Open or create a store-data database 
var Result = window.indexedDB.open ( 'store-data',. 3 ); 

// listener error function triggers 
result.onerror = function (Event) { 
  the console.log ( "the DataBase error: " , event.target.error); 
} 
// listens to upgrade the current version number is triggered when the function 
result.onupgradeneeded = function (Event) {
   var db = event.target.result;
   / * 
   contains the object repository name ( or call the table name). If you do not create one. 
   KeyPath object attribute id of the primary key 
  * / 
  IF (db.objectStoreNames.contains ( 'Store'! )) { 
    Db.createObjectStore ( "Store", {keyPath: "id", autoIncrement:to true }); 
  } 
} 

result.onsuccess = function (Event) {
   var targetValue = event.target.result;
   / *  
   1. Use targetValue.transaction (storeName, transactionMode) to create a transaction 
   2. After creating the transaction, we use targetValue. transaction (storeName, transactionMode) .objectStore ( storeName) 
   of this method, the object to get IDBObjectStore. 
  * / 
  Var objectStore = targetValue.transaction (storeName, TransactionMode) .objectStore (storeName);
   var Request = objectStore.add (ID {:. 3, name: 'kongzhi12', Age: 31 is }); 
  request.onsuccess = function (Event ) { 
    the console.log ('Successful callback' ); 
  } 
  request.onerror = function (Event) { 
    the console.log ( "the DataBase error:" , event.target.error); 
  } 
}

As the code, we opened or created a store-data database, then onsuccess callback attached to the request, on the onsuccess request, we have requested the event, then there is onsuccess callback functions, and so on, if the code is later to the more complex, we become after the code has been nested callbacks, so now we want to reconstruct the code above method using the promise, we want to make the above code becomes as follows like this:

openDatabase('store-data', 3).then(function(db) {
  return openObjectStore(db, "store", "readwrite");
}).then(function(objectStore){
  return addObject(objectStore, {"id": 3, "name": 'kongzhi123', 'age': 31});
}).then(function(){
  console.log('回调成功');
}).catch(function(error) {
  console.log('DataBase error', error);
});

We want to become the promise above code, we want to asynchronous callback javascript code becomes our promise code. Before the reconstruction of our code, we take a look at our XMLHttpRequest code, we want to use the promise to reconstruct the code before the reconstruction, we take a look at XMLHttpRequest code is as follows:

var XHR = new new the XMLHttpRequest (); 
xhr.onload = function () {
   // process the response 
}; 
xhr.onerror = function () {
   // handle error 
}; 
xhr.open ( "GET", '/xxx.json' , to true ); 
xhr.send ();

As such a code, the code is xmlHttpRequest our previous, now we can use our promise to reconstruct our above code, into the reconstructed code as follows:

var promise_XHR = function(url, method) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onload = resolve;
    xhr.onerror = reject;
    xhr.open(method, url, true);
    xhr.send();
  });
};

As promise_XHR function, which receives a url and method parameters, and a promise to return the object, the promise was introduced to a function that has two parameters, representing success and failure callbacks, then the internal code, we create a XMLHttpRequest object, then the object onload function of time to resolve the success callback assigned to him, and then when xhr.onerror function, the function passed to reject rejected him, the way we call as follows:

promise_XHR ( '/ xxx.json', 'GET'). the then ( function () {
   // processing is successful callback 
}). the catch (error) {
   // handling our exception callback 
}

Now we want to use this way to the interior of our store.js code. Reconstructed code becomes as follows:

Axios from Import 'Axios' ; 

var DB_VERSION =. 1 ;
 var the DB_NAME = 'Store-DATA2' ; 

var OpenDatabase = function () {
   return  new new Promise ( function (Resolve, Reject) {
     IF ! ( window.indexedDB) { 
      Reject ( " Not Supported indexedDB " ); 
    } 
    // open or create a store-data database 
    var Result = window.indexedDB.open (the DB_NAME, DB_VERSION); 

    // listener error function triggers 
    result.onerror = function (Event) { 
      the console.log ("The DataBase error:" , event.target.error); 
    } 
    // monitor the current version number is upgraded when the trigger function 
    result.onupgradeneeded = function (Event) {
       var DB = event.target.result;
       / * 
       contains the Object repository name (or called table name). If you do not create one. 
       KeyPath object attribute id of the primary key 
      * / 
      IF (db.objectStoreNames.contains ( 'Store'! )) { 
        Db.createObjectStore ( "Store", {keyPath: "id", autoIncrement: to true }); 
      } 
    } 
    Result .onsuccess = function (Event) { 
      Resolve (event.target.result); 
    } 
  });
};
 [];/ * 
 @Param {} storeName warehouse or table names in 
 @param {transactionMode} readOnly transaction read-only mode, readwrite readable and writable 
* / 
var openObjectStore = function (DB, storeName, TransactionMode) {
   return db.transaction (storeName, TransactionMode ) .objectStore (storeName); 
}; 

var getStore = function (successCallback) { 

  return  new new Promise ( function (Resolve, Reject) { 
    . OpenDatabase () the then ( function (DB) {
       var objectStore = openObjectStore (DB, 'Store' ) ;
       var DATAS = 
      objectStore.openCursor () onSuccess.= function(event) {
        var cursor = event.target.result;
        if (cursor) {
          datas.push(cursor.value);
          cursor.continue();
        } else {
          if (datas.length > 0) {
            resolve(datas);
          } else {
            getDataFromServer().then(function(d) {
              openDataBase().then(function(db) {
                var objectStore = openObjectStore(db, "store", "readwrite");
                for (let i = 0; i < datas.length; i++) {
                  objectStore.add(datas[i]);
                }
                resolve(datas);
              });
            });
          }
        }
      }
    }).catch(function() {
      getDataFromServer().then(function(datas) {
        resolve(datas);
      });
    });
  });
};

function getDataFromServer() {
  return new Promise(function(resolve, reject) {
    axios.get("http://localhost:8081/public/json/index.json", resolve);
  });
}

var addToObjectStore = function(storeName, object) {
  return new Promise(function(resolve, reject) {
    openDataBase().then(function(db) {
      openObjectStore(db, storeName, 'readwrite').add(object).onsuccess = resolve;
    }).catch(function(error) {
      reject(error);
    })
  });
};

var updateInObjectStore = function(storeName, id, object) {
  return new Promise(function(resolve, reject) {
    openDataBase().then(function(db) {
      openObjectStore(db, storeName, "readwrite").openCursor().onsuccess = function(event) {
        var cursor = event.target.result;
        if (!cursor) {
          reject("store-data not found");
        }
        if (cursor.value.id === id) {
          cursor.put(object).onsuccess = resolve;
          return;
        }
        cursor.continue();
      }
    }).catch(function(){
      reject(error);
    })
  });
}

window.openDataBase = openDataBase;
window.openObjectStore = openObjectStore;

window.addToObjectStore = addToObjectStore;
window.updateInObjectStore = updateInObjectStore;

window.getStore = getStore;

Then we need to change as shown in the following initialization code for our myAccount.js:

import $ from 'jquery';

$(function() {
  openDataBase("store-data2", 2).then(function(db) {
    return openObjectStore(db, "store", "readwrite");
  }).then(function(objectStore) {
    return addToObjectStore("store", {id: 1, name: 'kongzhi111', age: 11});
  }).then(function() {
    console.log('添加成功');
  }).catch(function(error) {
    console.log("数据库加载失败", error);
  });
  /*
  var addStore = function(id, name, age) {
    var obj = {
      id: id,
      name: name,
      age: age
    };
    addToObjectStore("store", obj);
    renderHTMLFunc(obj);
    $.getJSON("http://localhost:8081/public/json/index.json", obj, function(data) {
      updateDisplay(data);
    });
  };
  $("#submit").click(function(e) {
    addStore(3, 'longen1', '111');
  });
  $("#update").click(function(e) {
    $.getJSON("http://localhost:8081/public/json/index.json", {id: 1}, function(data) {
      updateInObjectStore("store", 1, data);
      updateDisplay(data);
    });
  });
  */
});

Then will insert a row into our database, we refresh the page to see our local database shown as follows:

 

github source code demo View

Guess you like

Origin www.cnblogs.com/tugenhua0707/p/11223556.html