封了个小程序请求

285 阅读1分钟

// 封装 api.js
const fetch = ({ url, params, method }) => {  
    return new Promise((resolve, reject) => {    
        wx.request({      
            url: getGlobal("host") + url,      
            method: method,      
            data: JSON.stringify(params),      
            dataType: "json",      
            header: {        
                "sessionid": wx.getStorageSync("sessionid")      
            },      
            success: res => {
                if (res.data.ret == 0) {          
                    return resolve(res.data);        
                }else {          
                    wx.showModal({            
                        title:'提示',            
                        content:res.msg,                
                        showCancel:false,          
                    })
                    return reject(res.data);
                }      
            },
            fail: err => {
                wx.showModal({
                    title:'提示',
                    content:'服务器繁忙,请稍后再试',          
                    showCancel:false,        
                })
                return reject(err);      
            }    
        });  
    });
};

// 定义接口
export const queryXXX = params => {
    return fetch({
        url:'xxxx.php',
        params:params,
        methods:'POST'
    })
}

// 使用 index.js
import {queryXXX} from './api.js';
queryXXX(){
    queryXXX({
        key1:val1,
        key2:val2
    }).then(res=>{
        console.log(res);
    })
}

抛砖引玉,请多指教,现在在寻求封装quertTask.abort()的方法.