微信小程序request异步问题解决方案

问题简介

  • onLoad()的同时又需要控制一个新定义的数组长度,此时会存在wx.request()的异步问题,即无法取到this.data.xxx

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    //已在data中定义section
    var that = this;
    var list = [{}];
    wx.request({
    url: 'https:(你所需要请求的地址)',
    header: {
    'content-type': 'application/json'
    },
    method: 'GET',
    dataType: 'json',
    responseType: 'text',
    success: function (res) {
    if (res.statusCode == 200) {
    that.setData({
    section: res.data
    })
    }
    }
    })
    console.log(this.data.section)//输出结果为空,即原始定义

解决方案

  • 直接将this.data.section的相关操作移到外部去。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    createList(){
    console.log(this.data.section)
    },
    onLoad(){
    ……省略
    success: function (res) {
    if (res.statusCode == 200) {
    that.setData({
    section: res.data
    })
    }
    that.createList() //输出为 section ,即res.data
    }
    ……省略
    }

拓展思路

  • 如果需要创建数组,其实可以进行套用此方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    createlist(){
    var list = [{}];
    for (let i = 0; i < this.data.section.length; i++) {
    list[i] = {};
    list[i].name = String.fromCharCode(65 + i);
    list[i].id = i;
    }
    this.setData({
    list: list,
    listCur: list[0]
    })
    },
    onLoad() {
    var that = this;
    wx.request({
    url: 'https://(你所需要请求的地址)',
    data: '',
    header: {
    'content-type': 'application/json'
    },
    method: 'GET',
    dataType: 'json',
    responseType: 'text',
    success: function (res) {
    if (res.statusCode == 200) {
    // console.log(res.data)
    that.setData({
    section: res.data
    })
    that.createlist()
    }
    },
    fail: function (res) { },
    complete: function (res) { },
    })

    },
  • 此时this.data.section可用于onLoad()地方。简单来说,就是由此所产生的问题,可直接将需要进行的操作移到onLoad()外部,然后再进行调用。

好了就这样啦~~ψ(`∇´)ψ

本文标题:微信小程序request异步问题解决方案

文章作者:puppetsheep

发布时间:2020年05月19日 - 01:10

最后更新:2020年05月20日 - 18:40

原始链接:https://puppetsheep.cn/2020/05/19/asynchronouscallback/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

打..打..打.....劫!
0%