使用Promise对微信小程序wx.request请求方法进行封装

/**

* 封装request请求

*

* 不要掉入回调的地狱中...

*/

function request(url, data = {}, method = "POST", ) {

  return new Promise(function(resolve, reject) {

      wx.request({

        url: url,

        data: data,

        method: method,

        header: {

          'Content-Type': 'application/json',

        },

        success: function (res) {

          if (res.statusCode == 200) {

            if (res.data.code == 0) {

              resolve(res.data);

            } else {

              wx.hideLoading();

              wx.showModal({

                title: '提示',

                content: res.data.msg,

                showCancel: false,

                success: function (res) { }

              })

              reject(res.data);

            }

          }else{

            wx.hideLoading();

            wx.showModal({

              title: '提示',

              content: '网络请求超时!',

              showCancel: false,

              success: function (res) { }

            })

            reject();

          }

        },

        fail: function (err) {

          wx.hideLoading();

          wx.showModal({

            title: '提示',

            content: '网络请求超时!',

            showCancel: false,

            success: function (res) { }

          })

          console.log("err", err);

          reject();

        }

      })

  })

}

/**

* 使用方法

*/

//引入封装的工具文件

const apiUtil = require('../../utils/ApiUtil.js');

var data = {

    name:"小明",

    age:18,

    sex:0

}

apiUtil.request("http://www.baidu.com", data).then(res => {

    console.log("请求成功")

}).catch(err => {

    console.log("请求失败")

})

---------------------

作者:春风十里柔情

来源:CSDN

原文:https://blog.csdn.net/qq_42196458/article/details/94460692

版权声明:本文为博主原创文章,转载请附上博文链接!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容