微信小程序利用promise封装request请求,添加finally事件

utils.js

const app = getApp();
const baseUrl = getApp().baseUrl;

//添加事件结束
Promise.prototype.finally = function (callback) {
    var Promise = this.constructor;
    return this.then(
        function (value) {
            Promise.resolve(callback()).then(
                function () {
                    return value;
                }
            );
        },
        function (reason) {
            Promise.resolve(callback()).then(
                function () {
                    throw reason;
                }
            );
        }
    );
}
const request = (url, method, data) => {
    return new Promise((resolve, reject) => {
        wx.request({
            url: url,
            data: data,
            method: method,
            header: {
                'content-type': 'application/json',
                'cld.stats.page_entry': Get('scene'),
                'token': Get('token'),
                'version': app.globalData.version
            },
            success: function (res) {
                if (res.statusCode == 200) {
                    resolve(res); //返回成功提示信息
                } else {
                    reject(res.data.message); //返回错误提示信息
                }
            },
            fail: function (res) {
                reject("网络连接错误"); //返回错误提示信息
            },
            complete: function (res) {

            }
        })
    });
}
module.exports = {
    request:request
}

js引用:

var app = getApp();
var baseUrl = getApp().baseUrl;
// import api from '../../utils/util.js';
const api = require('../../utils/util')

调用方法

api.request (url,methods ,data).then(res => {
      console.log('success:',res ); 
  }).catch(res => {
        console.log('fail:',res); 
  }).finally(()=>{
       console.log('finally:', "结束"); 
  })

 

你可能感兴趣的:(微信小程序,promise,request)