方法不唯一,后续有新方法再补上~

Promise 对象

let promise = new Promise(function(resolve, reject) {
if (/* 异步操作成功 */){
        resolve(value);
} else {
	reject(error);
}
});

promise.then(function(value) {
 // success
}, function(value) {
 // failure
});

关于promise 具体可参考阮老师的Promise 对象

或者直接

return new Promise(function (resolve, reject) {
  try{
    xxx
  }
  catch(e){ console.log(e) }
}

同步化异步函数

app.js

//app.js
function promisify(api) {
  return (opt, ...arg) => {
    return new Promise((resolve, reject) => {
      api(Object.assign({}, opt, { success: resolve, fail: reject }), ...arg)
    })
  }
}
App({
  request: promisify(wx.request),
  getUserInfo: promisify(wx.getUserInfo),
  onLaunch: function () {
    xxx
  },
  globalData: { }
})

index.js使用

let app = getApp();
Page({
  showdate: async function(){
    let res = await app.request({url:'xxx',,method:'POST',data:{x:0,y:1}})
    console.log(res)
  }
})

Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。

wx.request请求封装

异步

api/index.js封装

const getdata = function (url, data, callback) {
  wx.request({
      url: url,
      data: data,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        return typeof callback == "function" && callback(res.data)
      },
      fail: function (res) {
        return typeof callback == "function" && callback(false)
      }
  })
}

const postdata = function (url, data, callback) {
  wx.request({
      url: url,
      data: data,
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        return typeof callback == "function" && callback(res.data)
      },
      fail: function (res) {
        return typeof callback == "function" && callback(false)
      }
  })
}

module.exports = {
  getdata,
  postdata
}

app.js引入

const api = require('./api/index
App({
  onLaunch: function () {
    xxx
  },
  globalData: {
    api
  }
})

index.js使用

const app = getApp();
const api = app.globalData.api
Page({
  api.getdata("xxx", {},
  function (res) {
    console.log(res);
  });
  api.postdata("xxx", {x:0,y:1},
  function (res) {
    console.log(res);
  });
})

同步

app.js引入

function promisify(api) {
  return (opt, ...arg) => {
    return new Promise((resolve, reject) => {
      api(Object.assign({}, opt, { success: resolve, fail: reject }), ...arg)
    })
  }
}
App({
  request: promisify(wx.request)
})

index.js使用

const app = getApp();
Page({
  showdate: async function(){
    let res = await app.request({url:'xxx',method:'GET'})
    console.log(res);
  })
})

参考