【问题标题】:How to use localForage synchronously如何同步使用localForage
【发布时间】:2019-07-01 07:51:31
【问题描述】:

我有一个 Cordova 移动应用程序,可将离线数据存储在 localStorage 中。最近用户开始收到 QUOTA_EXCEEDED_ERR 错误,因为 localStorage 有 5MB 限制。我决定使用“localForage”框架,但我注意到它是异步工​​作的。由于我不想将所有复杂的应用程序重写为回调函数,因此我想知道是否有某种方法可以同步使用“localForage”(等到 getItem 函数返回值)。

这是我正在尝试做的代码示例:

localforage.setItem('testKey', 'testValue', function() {
  var value = getValue('testKey');

  console.log(value); // here I get undefined, but I want to get a value
});

function getValue(key) { // I want this function to return value
  var result;
    localforage.getItem(key, function(value) {
    result = value;
  });

  return result;
}

我希望 getValue() 在不更改任何其他代码的情况下返回一个值

【问题讨论】:

    标签: javascript callback local-storage localforage


    【解决方案1】:

    据此link

    localForage 有一个双重 API,允许您使用 Node 样式 回调或承诺。如果您不确定哪一款适合您, 建议使用 Promises。

    因此,您可以根据需要使用其中的任何一个。如果使用 Promise,您可以使用 async/await 等待结果

    localforage.setItem('testKey', 'testValue', async function() {
      var value = await getValue('testKey')
    
      console.log(value); // here I get undefined, but I want to get a value
    });
    
     async function getValue(key) { 
      var result = await localforage.getItem(key);
      return result;
    }
    

    jsfiddle

    【讨论】:

    • 我试过这种方式,但它也不起作用:/。见:jsfiddle.net/kqf5xvz7
    • 是的,但现在我需要将所有调用 getValue 的函数更改为异步。我想换一个地方,不要破坏这个旧的脆弱的应用程序:)
    • 我认为没有其他方法。由于 async 的性质,您必须阻止代码继续前进,除非您有数据并且为此您必须使用 callbacksasync/await
    【解决方案2】:
    localforage.setItem('testKey', 'testValue', async function() {//declare function as async
      var value = await getValue('testKey'); //wait for the value
    
      console.log(value); // "testValue" value should show in console
    });
    
    //declare function as async
    async function getValue(key) {
      var result = await localforage.getItem(key); //wait for the localforage item
    
      return result;
    }
    

    这里的JSFiddle:https://jsfiddle.net/mvdgxorL/

    【讨论】:

      【解决方案3】:

      https://localforage.github.io/localForage/#data-api-getitem,使用async/await

      try {
          const value = await localforage.getItem('somekey');
          // This code runs once the value has been loaded
          // from the offline store.
          console.log(value);
      } catch (err) {
          // This code runs if there were any errors.
          console.log(err);
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-20
        • 1970-01-01
        • 2021-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-20
        • 2016-03-06
        • 2017-06-24
        相关资源
        最近更新 更多