小程序为了避免回调地狱,Promise化API简析

首先先了解一下什么叫回调地狱,“回调地域”指的是,多级的异步的嵌套调用的问题。

这种情况在前端开发中很常见,通过ajax/axios请求callback中拿到所需的值再把此值作为参数再发起请求。(可嵌套N层)

所以我们遇到这种情况就需要封装请求,避免产生回调地狱(可读性差不利于维护容易产生许多问题等)。

一、首先要使用Promise封装请求API:(uniapp示例,也可以改写成原生)

class Request {
  constructor(options = {}) {
    // 请求的根路径
    this.baseUrl = options.baseUrl || ''
    // 请求的 url 地址
    this.url = options.url || ''
    // 请求方式
    this.method = 'GET'
    // 请求的参数对象
    this.data = null
    // header 请求头
    this.header = options.header || {}
    this.beforeRequest = null
    this.afterRequest = null
  }

  get(url, data = {}) {
    this.method = 'GET'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  post(url, data = {}) {
    this.method = 'POST'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  put(url, data = {}) {
    this.method = 'PUT'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  delete(url, data = {}) {
    this.method = 'DELETE'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  _() {
    // 清空 header 对象
    this.header = {}
    // 请求之前做一些事
    this.beforeRequest && typeof this.beforeRequest === 'function' && this.beforeRequest(this)
    // 发起请求
    return new Promise((resolve, reject) => {
      let weixin = wx
      // 适配 uniapp
      if ('undefined' !== typeof uni) {
        weixin = uni
      }
      weixin.request({
        url: this.url,
        method: this.method,
        data: this.data,
        header: this.header,
        success: (res) => { resolve(res) },
        fail: (err) => { reject(err) },
        complete: (res) => {
          // 请求完成以后做一些事情
          this.afterRequest && typeof this.afterRequest === 'function' && this.afterRequest(res)
        }
      })
    })
  }
}

export const $http = new Request()

二、使用前先记得在main.js上挂载:

// 按需导入 $http 对象
import {
	$http
} from '/class/request.js'
$http.baseUrl = '你的接口地址'
uni.$http = $http

三、使用async,配合await解构出res:

async fetchInfo() {
    const { data: res } = await uni.$http.get('/api/public/v1/xxxx')
    console.log(res)
    let params = {
        id: res
    }
    const { data: res1 } = await uni.$http.post('/api/public/v1/yyyy', params)
    console.log(res1)
    //如有err/succ
    const [err, succ] = await uni.$http.post('/api/public/v1/yyyy', params)
    console.log(succ)
    if(res1.status === 200) return //...do something
}

结语:使用ES6特性Promise把请求代码写得优雅起来吧~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值