微信小程序(一)onload函数异步处理的解决方案 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 小程序相关 >

微信小程序(一)onload函数异步处理的解决方案

发表时间:2020-9-28

发布人:葵宇科技

浏览次数:142

微信小程序(一)onload函数异步执行的解决方案

  • 写作目的
  • 解决方案一
  • 解决方案二

写作目的

这两天把前几个月写的小程序整理了一下,发现实际连上服务器之后会发生网络错误,主要是因为onload里加载了若干个个wx.request函数,有的函数的参数依赖于其他函数的返回值。

而由于微信小程序的onload函数是异步执行的,导致先执行的函数尚未返回参数,后续函数就已经开始运行,最终产生错误。

解决方案一

使用Promise或者回调函数来保证程序按照你想要的顺序执行
sample:getDish()方法需要先执行get_shop_info()方法获取数据

// 使用promise
 getDish:function(e){

  this.get_shop_info().then(res =>{ //请求成功的时候进行下一步流程,这样就可以避免异步问题

    console.log(res);

  }).catch(err =>{  //请求失败

    console.log(err);

  });
}

 get_shop_info:function(e){   //需要先执行的方法

  return new Promise((reslove, reject) => {
    wx.request({   //请求接口的异步操作
      url: ‘’, //接口地址
      method: method || 'GET',
      data:‘’, //参数
      success: (res) => {
          reslove(res.data, res);
      },
      fail: (msg) => {
        reject('请求失败');
      }
    })
  });
}

回调函数虽然也可以解决问题,但由于层级多了以后代码会显得非常混乱,因此不推荐使用。

解决方案二

可以把需要得到的数据从上级页面传回,或写入全局数据/缓存,在新页面执行onload函数时通过setdata获取。

sample:在登录界面向全局写入shop_id信息,在新页面的onload函数中读取

// 新页面的onload函数
>: function (options) {    
    var that = this
    that.setData({
      //注意此处是that.setData而不是this
      shop_id:app.globalData.shop_id,
      
    })
    //写入数据后再执行包含request请求的函数
    this.getType()
    this.getDish()
    this.get_train_info()
    this.get_record_info()
    app.getUserInfo(function (userInfo) {
      that.setData({
        userInfo: userInfo,
        img: userInfo.avatarUrl
      })
    })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({ 
          height: (res.windowHeight*.57)+'px'
        })
      }
    });
  },
  
// 在上层页面写入全局信息
  login: function () {
    var that = this;
    var type = "upload"
    if (this.data.username.length == 0 || this.data.password.length == 0) {
      wx.showToast({
        title: '账号或密码不能为空',
        icon: 'none',
        duration: 2000
      })
    } 
    else {
      wx.request({
        url: 'http://127.0.0.1:5000/login', // 仅为示例,并非真实的接口地址
        method: 'post',
        data: {
          username: this.data.username,
          password: this.data.password
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success(res) {
          if (res.data.flag==1) {
            wx.setStorage({
              key: 'rd_session',
              data: 1
            });
            app.globalData.shop_id = res.data.shop_id
            console.log(app.globalData.shop_id)
            wx.navigateTo({//跳转至下级界面
              url: '/pages/index/index' ,
            })

          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
      
      console.log(this.data.logflag)
    }
  }
// 别忘了在app.js里初始化全局数据
globalData: {

    shop_id:0,

  }

comments are welcome!

相关案例查看更多