首页 新闻 会员 周边

仿造jq ajax封装request.js,js不太专业,请问我这样的封装合格不?有没有bug以及可优化的点呢?

0
悬赏园豆:20 [待解决问题]
/**
 * 仿jq ajax  
 * by练涛  2021.1.20
 * @param {*} obj 
 */
const myajax = (obj = { url, headers, timeout, method, dataType, data, success, fail, complete }) => {
    //入参类型检测,如果不符合预期则,抛出异常
    if (typeof obj.url != "undefined" && typeof obj.url != 'string') throw new TypeError('url不是string类型');
    if (typeof obj.headers != "undefined" && typeof obj.headers != "object") throw new TypeError('headers不是object类型');
    if (typeof obj.timeout != "undefined" && typeof obj.timeout != 'number') throw new TypeError('timeout不是number类型');
    if (typeof obj.method != "undefined" && typeof obj.method != 'string') throw new TypeError('method不是nstring类型');
    if (typeof obj.dataType != "undefined" && typeof obj.dataType != 'string') throw new TypeError('dataType不是string类型');
    if (typeof obj.data != "undefined" && typeof obj.data != 'object' && !ArrayBuffer.isView(obj.data)) throw new TypeError('data不是object类型或者ArrayBuffer');
    if (typeof obj.success != "undefined" && typeof obj.success != 'function') throw new TypeError('success不是function类型');
    if (typeof obj.fail != "undefined" && typeof obj.fail != 'function') throw new TypeError('fail不是function类型');
    if (typeof obj.complete != "undefined" && typeof obj.complete != 'function') throw new TypeError('complete不是function类型');
    return new Promise((resolve, reject) => {
        my.request({
            url: devUrl + obj.url,  //不会有人不写url吧。。。url!=""   
            method: obj.method || 'GET',   //默认get
            dataType: obj.dataType || 'json',   //默认json
            headers: obj.headers || null,
            timeout: obj.timeout || 30000,   //默认30000
            data: obj.data || null,
            success: (res) => {
                if (typeof obj.success == 'function') {
                    obj.success(res);
                }
            },
            // 当程序出错或是网络请求失败都会执行该方法
            fail: (res) => {
                reject(res);
                if (typeof obj.fail == 'function') {
                    obj.fail(res);
                }
            },
            complete: function (res) {
                //调用结束的回调函数(调用成功、失败都会执行)。
                if (typeof obj.complete == 'function') {
                    obj.complete(res);
                }
            }
        });
    })
}

仿造jq ajax封装request.js,js不太专业,请问我这样的封装合格不?有没有bug以及可优化的点呢?

练涛的主页 练涛 | 初学一级 | 园豆:12
提问于:2021-02-04 10:30
< >
分享
所有回答(2)
0

合格,没有bug,无需优化,完美

不知道风往哪儿吹 | 园豆:2035 (老鸟四级) | 2021-02-04 11:03

认真的吗....

支持(0) 反对(0) 练涛 | 园豆:12 (初学一级) | 2021-02-05 17:08
0

排版完美,注释清晰,字迹整洁,最重要的不是方正字体

永远跟党走i | 园豆:1519 (小虾三级) | 2021-02-08 19:19

真实。。

支持(0) 反对(0) 练涛 | 园豆:12 (初学一级) | 2021-02-09 10:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册