小程序发送请求的异步操作探索

回调

一开始的时候使用回调的方式写统一调用小程序发送请求的接口。

准备数据 => 发送请求 => 执行回调
function CGI(yurl, type, data, success, err) {
  var version = getVersion();
  var uoAuth = getUoAuth();
  var uoSign = getUoSign();
  var url = getTrueUrl(yurl);
  if (uoAuth && uoSign) {
    data.uoAuth = uoAuth;
    data.uoSign = uoSign;
  }
  //上面获取登陆状态,和参数的东西,无视
  type = type.toUpperCase();
  var contentType = 'application/json';
  if (type == "POST") {
    contentType = 'application/x-www-form-urlencoded';
  }
  wx.request({
    url: url,
    data: data,
    method: type,
    header: {
      'content-type': contentType
    },
    success: function (res) {
        if(res.data.errCode == 1) {
          login();
          return ;
        }
        typeof success == "function" && success(res.data);
    },
    fail: function (res) {
      wx.showToast({
        title: res.msg || '网络访问失败',
        duration: 1500
      });
      typeof err == "function" && err(res.data);
    }
  })
}
复制代码

Promise

将回调改写成 Promise 的方式调用

准备数据 => 发送请求 => 返回 Promise 对象 => then
/*
  Promise 接口调用函数
*/
function PCGI(yurl, type, data, success, err) {
  console.log('PCGI')
  var version = getVersion();
  var uoAuth = getUoAuth();
  var uoSign = getUoSign();
  var url = getTrueUrl(yurl);
  if (uoAuth && uoSign) {
    data.uoAuth = uoAuth;
    data.uoSign = uoSign;
  }

  type = type.toUpperCase();
  var contentType = 'application/json';
  if (type == "POST") {
    contentType = 'application/x-www-form-urlencoded';
  }
  return new Promise((resolve,reject)=>{
    wx.request({
      url: url,
      data: data,
      method: type,
      header: {
        'content-type': contentType
      },
      success: function (res) {
        if (res.data.errCode == 1) {
          login();
          return;
        }
        resolve(res.data)
      },
      fail: function (res) {
        wx.showToast({
          title: res.msg || '网络访问失败',
          duration: 1500
        });
        reject(res.data);
      }
    })
  })
}
复制代码

generator + co

在 PCGI 的基础上改造,支持并发请求

准备数据 => 发送请求 => 返回 Promise 对象 => then
const HEADER = {
  'GET':{
    'content-type': 'application/json'
  },
  'POST': {
    'content-type':'application/x-www-form-urlencoded'
  }
}
function getTrueUrl(url){
  //...
}

function promiseReq(item){
  let method = 'GET';
  var uoAuth = getUoAuth() || '';
  var uoSign = getUoSign() || '';
  let config = {
    url: '',
    data: {uoAuth, uoSign},
    method,
  }
  return new Promise((resolve,reject)=>{
    if (isString(item)){
      config.url = getTrueUrl(item);
    }else{
      let { url, type='GET', data } = item;
      config.url = getTrueUrl(url);
      config.data = data ? Object.assign(config.data, data) : config.data;
      config.method = type && type.toUpperCase() || method;
    }
    config.header = HEADER[config.method];
    
    config.success = (res) => resolve(res.data)
    config.fail = (err) => reject(err)

    wx.request(config);
  })
}


function requestFn(request) {
  console.log('requestFn')
  function* task() {
    try {
      var result;
      if(isArray(request)){
        result = yield Promise.all(request.map((item, index, arr) => promiseReq(item)))
      }else{
        result = yield promiseReq(request)
      }
      console.log(result)
      return result;
    } catch (e) {
      console.log(e)
    }
  }
  return co(task)
}
复制代码

async / await

在 generator + co 的基础上使用 async / await 改造

准备数据 => 发送请求 => 返回 Promise 对象 => then
function promiseReq(item){
  let method = 'GET';
  var uoAuth = getUoAuth() || '';
  var uoSign = getUoSign() || '';
  let config = {
    url: '',
    data: {uoAuth, uoSign},
    method,
  }
  return new Promise((resolve,reject)=>{
    if (isString(item)){
      config.url = getTrueUrl(item);
    }else{
      let { url, type='GET', data } = item;
      config.url = getTrueUrl(url);
      config.data = data ? Object.assign(config.data, data) : config.data;
      config.method = type && type.toUpperCase() || method;
    }
    config.header = HEADER[config.method];
    
    config.success = (res) => resolve(res.data)
    config.fail = (err) => reject(err)

    wx.request(config);
  })
}

function asyncRequest(request) {
  console.log('asyncRequest')
  return (async () => {
    try {
      return isArray(request) ? await Promise.all(request.map((item, index, arr) => promiseReq(item))) : await promiseReq(request);
    } catch (e) {
      console.log(e)
    }
  })()
}
复制代码

转载于:https://juejin.im/post/5be8fae8f265da616b103b5c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值