tantaman / LargeLocalStorage

Problem: You need to store a large amount of key-value based data in IE, Chrome, Safari, AND Firefox
MIT License
531 stars 48 forks source link

how to get the return value #4

Closed zacksleo closed 6 years ago

zacksleo commented 9 years ago

hi @tantaman:

Question

I'm confused when using the LLS in my code. I don't know how go get the return value in the function getData because it's async which is beyond my expect. In the console, the function getData always return null (Line 65), "4:end" is print before others ("like 3.1 or 3.2")

Could you tell me what should I do ?

Code


define(function(require, exports, module){
  var $ = require('jquery');
  $.ajaxSettings.async = false;
  var LargeLocalStorage = require('largeLocalStorage/largeLocalStorage');
  // for debug : window.lls = LargeLocalStorage;

  /**
   *get Local Data 获取数据
   * @param {String} name
   * @returns {JSON}
   */
  exports.getData = function(name){
    var value = null;
    var storage = new LargeLocalStorage({
      size: 20 * 1024 * 1024,
      name: 'lls-ezts-db'
    });
    storage.initialized.then(function(){
      storage.getContents(name, {json: true}).then(function(contents){
        value = content;
      }).then(function(contents){
        /**
         * local data unavailable  本地缓存数据不存在
         */
        if(typeof (contents) == "undefined" || contents == null){
          console.log('1.1:local data unavailable 本地无数据');
          var refer = getLocalStoreControlByName(name);
          if(refer){
            $.getJSON(refer.url, function(result){
              storage.setContents(name, result, {json: true});
              storage.setContents(name + '-update-time', refer.update_time);
              value = result;
              return value;
              console.log('1.2:Server data request success 数据请求成功');
            });
          }
          console.log('1.3:get server data success 数据获取成功');
          /**
           * 本地缓存数据存在
           */
        }else{
          var update_time = storage.getContents(name + '-update-time');
          var refer = getLocalStoreControlByName(name);
          /**
           * Update local data which is expired 本地缓存数据过期,更新缓存
           */
          if(typeof (update_time) == "undefined" || update_time < refer.update_time){
            console.log('2.1:local data expired 本地缓存数据过期');
            $.getJSON(refer.url, function(result){
              storage.setContents(name, result, {json: true});
              storage.setContents(name + '-update-time', refer.update_time);
              value = result;
              return value;
            });
          }else{
            console.log('3.1: local data available 本地缓存数据可用');
            console.log('3.2:local data is 本地缓存数据为' + value);
            value = contents;
            return contents;
          }
        }
      });
    });
    console.info('4:end 结束:' + value);
    return value;
  };
  /**
   * 查找缓存控制对照表
   * @param {String} name
   * @returns {Object}
   */
  function getLocalStoreControlByName(name){
    var dict = window.localStorageControl;
    for(var i = 0; i < dict.length; i++){
      if(dict[i].name == name){
        return dict[i];
      }
    }
  }
});
tantaman commented 9 years ago

LLS has to be async since the FilesystemAPI, IndexedDB and WebSQL (the implementations behind large local storage) are all a-sync. You would get the return value much like you would get the value from an event handler in jQuery.

storage.getContents(name, {json: true}).then(function(contents){
       // You have the return value of getContents here in the `contents` variable
    })

For your situation, you should be able to just move the code that needs the return value into the callback that is receiving the return value.

Right now you have:

storage.getContents(name, {json: true}).then(function(contents){ // first then
        value = contents;
      }).then(function(contents) { // second then
         ...more code...
      })

You can remove the first then enitrely or return a value from the first then so it can be passed to the second then Right now nothing is passed to the second then since nothing is returned from the first then.

Also, your statement value = content has a typo. If you are going to keep it it should be value = contents although I don't see why you need the firstthen at all.