收藏
回答

小程序wx.setStorageSync后,在用getStorageSync获取数据有时会获取不到

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 Bug 数据缓存 微信iOS客户端 7.0.12 2.10.4

https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageSync.html


这个页面的两种获取方法都测试过,还是偶尔出现获取不到的情况

回答关注问题邀请回答
收藏

4 个回答

  • o0o有脾气的酸奶
    o0o有脾气的酸奶
    2020-04-21
    同步异步的问题
    app.js
    
    getUserId: async function(data){
      // 优先使用缓存数据
      var cacheUid = wx.getStorageSync('userId') || this.globalData.userId || 0
      if(cacheUid) {
        this.globalData.userId = cacheUid
        wx.setStorageSync('userId', cacheUid)
        return {code:200, userId:cacheUid, message:''}
      }
    
      // 缓存数据不存在,再请求接口,并缓存数据
      var  res = await util.request(api.GetUserId, data, 'POST')
      var uid = res.code == 200 ? res.data : 0
      res.code != 200 && console.log('getUserId:', res.message);
      this.globalData.userId = uid
      wx.setStorageSync('userId', uid)
      return {code:res.code, userId:uid, message:res.message}
    }
    
    pages/test/test.js
    var app = getApp()
    
    onShow: async function() {
      var data = 'xxxxx'
      let {userId,message} = await app.getUserId(data)
      if (userId) {  
        this.setData({
          userId: userId,
        })
      }else{
        wx.showToast({
          title:message,
          icon:'none',
          mask:true
        })
      }
    }
    

    若认为该回答有用,给回答者一个[ 有用 ]吧!!

    2020-04-21
    有用 1
    回复
  • 拾忆
    拾忆
    2020-04-21

    这个很正常,2个本来就是异步执行的~

    2020-04-21
    有用 1
    回复 2
    • LDemon
      LDemon
      2020-04-21
      如果要想缓存一个数据,并且能实时获取到,要怎么做呢
      2020-04-21
      回复
    • 拾忆
      拾忆
      2020-04-21回复LDemon
      在请求成功后操作读写缓存~
      使用async/await~

      或者用定时器轮询,什么时候有缓存了删除定时器~
      2020-04-21
      回复
  • Admin ²º²³
    Admin ²º²³
    2020-04-21

    这个有这种情况:

    app.js里的请求还没返回时,show里面就去获取了。这个时候会失败

    app.js里用await等待执行吧

    2020-04-21
    有用
    回复
  • LDemon
    LDemon
    2020-04-21

    app.js

    util.request(api.GetUserId, data, 'POST').then(res => {

    if (res.code == 200) {

    this.globalData.userId = res.data

    wx.setStorageSync('userId', res.data)

    } else {

    // util.showErrorToast(res.message);

    }

    })


    pages/test/test.js

    onShow: function() {

    try {

    let userId = wx.getStorageSync('userId')

    if (userId) {

    this.setData({

    userId: userId,

    })

    }

    } catch (e) {

    // Do something when catch error

    }


    2020-04-21
    有用
    回复
登录 后发表内容
问题标签