uniapp 中setStorageSync 与setStorage区别

235 阅读1分钟

 uni.setStorage: 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。

uni.setStorage({
  key: 'storage_key',
  data: 'hello',
  success: function () {
      console.log('success');
  }
});

uni.setStorageSync: 将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口

try {
    uni.setStorageSync('storage_key', 'hello');
} catch (e) {
    // error
}

区别: 他们之间的区别就是线程,一个是异步执行,无需等待,继续执行下面的操作,一个同步执行,必须执行完成存储之后才能执行下面的操作!

注意 在不同的平台,对应的使用范围不一样 H5:用的是缓存的概念,有限制localStorage,可能会被清除 APP:肯定是持久化操作,没有限制的,需要考虑的是大量的缓存积累会导致APP 运行变慢,解决方案是对缓存的数据做时间限制,到期清除

if (finalKey && value) {
        const expire = nowTime + Number(seconds);
        uni.setStorageSync(finalKey, `${JSON.stringify(value)}|${expire}`)
        console.log(`已经把${finalKey}存入缓存,过期时间为${expire}`)
    }else if (finalKey && !value) {
        const val = uni.getStorageSync(finalKey);
        if (val) {
            // 缓存存在,判断是否过期
            const temp = val.split('|')
            if (!temp[1] || temp[1] <= nowTime) {
                uni.removeStorageSync(finalKey)
                console.log(`${finalKey}缓存已失效`)
                return '';
            }
            return JSON.parse(temp[0]);

        }
        }

小程序情况特殊,基本上每个平台都会对缓存大小或则key 值字符串长度进行限制,超出自动删除,具体情况根据平台要求查看