weex中使用promise封装一个网络请求

2019-01-04 06:24
椰子皮
3884
2
7
移动端

“ 混合app开发 ”

最近需要一款app,在技术选型上敲定了阿里的weex,一顿操作下来,各种不兼容突然看到了大佬基于weex封装的weexplus,然后就开始漫长的混合app开发之旅,weexplus帮我解决不不少难题,下面字段代码是基于weex内置模块封装的,

复制代码
ajax(method, url, params) {
  return new Promise((resolve, reject) => {
    const stream = weex.requireModule('stream');
    stream.fetch({
      method,
      url: `${this.baseUrl}${url}`,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
         Accept: 'application/json, text/plain, */*',
         Authorization: 'token',
      },
      body: method === 'get' ? '' : JSON.stringify(params),
      type: 'json',
    }, (res) => {
       if (res.status === 200) {
            resolve(res);
       } else {
            reject(res);
       }
   }, () => {
        // complete
     });
  });
},

写在mixins里面全局调用

复制代码
$get(url, params) {
  return this.ajax('get', url, params);
},

搭配async await 使代码更简洁

复制代码
mounted() {
  this.getList()
},
methods: {
  async getList() {
    const { data } = await this.$get('app/shuffling_image', { page: 1, pageSize: 5 })
  }
}

也可以搭配async await 使用

赏
支付宝微信
7
关注公众号获取更多内容
vuex action 与mutations 的区别
小程序canvas绘制圆形图片并且居中
共有 1 条评论
发表评论
  • Paul#10049
    2019-09-25 18:28
    湖南省湘潭市雨湖区
    Win7

    大佬6啊。个人觉得评论的话尽量不用验证码,影响用户体验

    回复
    • 椰子皮#10140
      2019-09-25 19:30
      湖南省湘潭市雨湖区
      Win7
共 1 条 第 1-1 条
每页
10
条
  • 1
不支持canvas