默认的写法实在受不了,特别是各种回调的嵌套

request.js

const s = require("./sign.js");
const serial = require("./serial.js");
const msg = require("./msg.js");
var x = {};
x.config = {};
x.data = {};
x.loadingText = "";

x.setConfig = function(config)
{
    x.config = config;
    return x;
};

x.setData = function(data)
{
    x.data = data;
    return x;
};

x.setSuccess = function(f)
{
    serial.add(f);
    return x;
};

x.setLoadingText = function(text)
{
    x.loadingText = text;
    return x;
};

x.run = function(name)
{
    var config = x.config;
    var appKey = config.appKey;
    var domain = config.domain;
    var list = config.list;
    var item = list[name];
    if(item.domain == ""){
        item.domain = domain;
    }
    var url = item.domain + "/" + item.url;
    var header = {};
    if(item.method == "GET"){
        header = {"content-type": "application/json"};
    }
    else if(item.method == "POST"){
        header = {"content-type": "application/x-www-form-urlencoded"};
    }
    var data = x.data;
    if(item.sign == "1"){
        data = s.sign(appKey, data);
    }
    
    function success(response)
    {
        serial.run(response);
    }
    
    function fail(response)
    {
        if(response.errMsg == "request:fail timeout"){
            msg.sure("信息", "网络超时,请重试");
        }
    }
    
    function complete()
    {
        serial.clear();
        if(x.loadingText != ""){
            x.setLoadingText("");
            setTimeout(msg.hideLoading, 500);
        }
    }
    
    if(x.loadingText != ""){
        msg.showLoading(x.loadingText);
    }
    wx.request({url: url, data: data, method: item.method, header: header, success: success, fail: fail, complete: complete});
};

module.exports = x;

使用方法如下

app.js需要全局注册

r: function(){
    return request.setConfig(config);/*接口配置清单*/
}

页面代码

var data = {};/*请求数据*/
app.r().setData(data).setSuccess(app.msg.ifFailStop).setSuccess(success).setLoadingText("正在加载数据").run("getProductList");

其中setSuccess可以设置请求成功后的回调函数,嵌套的回调被串行化了,依次执行


xxfaxy
1.6k 声望18 粉丝