Small program solves the request interface problem in the for loop

The interfaces of WeChat applets are all asynchronous, if you use a for loop

    var arr = [];
    for(var i = 0;i<5;i++){
      wx.request({
        url: '',
        header: {
          'content-type': 'application/json', // 默认值
          "Authorization": 'Bearer ' + wx.getStorageSync('token'),
        },
        success(resp) {
          arr.push(resp.data)
        }
      })
    }
    setTimeout(function(){
      console.log(arr);
    },1000)

It is not easy to use timers to control the time required for interface requests, and this method is too low in availability in actual operations.

Can be replaced by recursion

getammeternumber:function(res,i,length){
    var that = this;
    var ammeterInfo = that.data.ammeterInfo;
    wx.request({
      url: '',
      header: {
        'content-type': 'application/json', // 默认值
        "Authorization": 'Bearer ' + wx.getStorageSync('token'),
      },
      success(resp) {
        ammeterInfo.push(resp.data);
        that.setData({
          ammeterInfo: ammeterInfo
        })
        if (++i< length) {
          that.getammeternumber(res, i, length);
        }else{
          wx.hideLoading();
        }
      }
    })
  },

transfer:

that.getammeternumber(res, 0, res.data.length);

Guess you like

Origin blog.csdn.net/qq_37514029/article/details/88683212