Mini Program request request

I would like to ask you a question. I wrote a public function, in app.js. The function contains request, and then return returns the value. Now the problem is that request is an asynchronous request. When the request is not finished, a null value will be passed. How to solve this problem?

Mar.03,2021

your public function takes a function as an argument.
request executes this callback function parameter when it gets the return value of the request.

  //app.js
  getUserInfo (callback) {
    if (this.globalData.user) {
      callback(this.globalData.user)
    } else {
        wx.request({
            url: 'xxx',
            method: 'POST',
            data: {},
            success: res => {
                this.globalData.user = res.data.data
                callback(res.data.data)
            }
        })
    }
  }

  // index.js
  onLoad() {
    app.getUserInfo(this.getList) // getUserInfogetList
  }

or, your public function returns a Promise function, resolve it when you get the return value.

//app.js
getUserInfo () {
  return new Promise((reslove, reject) => {
    if (this.globalData.user) {
      resolve(this.globalData.user)
    } else {
        wx.request({
            url: 'xxx',
            method: 'POST',
            data: {},
            success: res => {
                this.globalData.user = res.data.data
                resolve(res.data.data)
            }
        })
    }
  })
}

  // index.js
onLoad() {
    app.getUserInfo().then(res => {
        console.log(res)  //  res getUserInfo resolve 
    })
}

export let http = ({url,method,data}) => {
  let p = new Promise((resolve,reject) => {
    wx.request({
      url,
      data,
      method,
      header: {'content-type':'application/json'},
      success: resolve,
      fail: reject
    })
  })
  return p;
}
use import {http} from'. / async.js';
export let getList = (data) => {
  return http({
          url: `${}${}`,
          method:'get',
          data
        })
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e3f229-44825.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e3f229-44825.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?