微信小程序回调函数理解

微信小程序的onLaunch和onLoad异步执行可能导致数据同步问题。当onLaunch的网络请求较慢,index.js的onLoad可能先执行,这时需通过回调函数确保数据的正确传递。本文探讨两种情况:1. onLaunch请求慢,onLoad通过回调函数获取数据;2. onLaunch快速完成,直接在onLoad中处理网络返回值。

由于微信小程序app.js页面中的onLaunch和其他js页面中的onLoad属于异步执行。有时onLaunch中会有网络请求,在等待网络返回值时,其他js页面中的onLoad已经执行了。这时就会导致onLoad中会接收到空数据,而接收不到网络返回值。为了解决上述问题,可以使用回调函数。

可分为两种情况:

一、onLaunch网络请求时间较长,index.js中的onLoad先加载完成

此时在index.js页面中,没有获取到网络返回值,common.getNewsList()[0].id返回为null,所以进入else分支,在else中定义回调函数。当onLaunch中网络请求完成,继续向下进行时,会启动回调函数,进行赋值。

二、onLaunch加载较快,onLoad中获取到网络返回值

这时执行if分支,不再定义回调函数。

//app.js
//请求信息
 App({
  onLaunch: function () {
    var that = this;
    wx.request({
      url: 'https://v.juhe.cn/', //略写
      data: {
        x: "",
        y: ""
      },
      success: function (res) {
        console.log(res.data);
        let list = [];
        for (var i = 0; i < 4; i++) {
          let obj = {};
          obj.id = res.data.result.data[i].uniquekey;
          obj.title = res.data.result.data[i].title;
          obj.date = res.data.result.data[i].date;
          obj.url = res.data.result.data[i].url;
          obj.poster = res.data.result.data[i].thumbnail_pic_s;
          list.push(obj);
        }
        that.globalData.newsList = list;
        if(that.readyCallback){
          that.readyCallback(res)			//回调函数
        }
      }
    })
    },
    globalData: {
    userInfo: null,
    newsList:[
      {
        id:"null",
        title:"",
        poster:"",
        date:"",
        url:""
      }
    ]
  }
 }
//index.js
onLoad: function (options) {
    if (common.getNewsList()[0].id!="null")       //回调函数用法较为灵活,需按项目进行编写
    {
      //获取列表
      let list = common.getNewsList();
      //更新列表数据
      this.setData({ newsList: list })
    }else{
      app.readyCallback = res =>{
        //获取列表
        let list = common.getNewsList();
        //更新列表数据
        this.setData({ newsList: list })
      }
    }
  }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值