js使用promise封装ajax


Promise将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数

代码:

function ajaxPromise(url,method,data) {
                var pro = new Promise(function(resolve, reject) {
                    var ajax = new XMLHttpRequest();
                    var method=method||"GET"
                     var data=data ||null
                    ajax.open(method, url);
                    ajax.send(data);
                    ajax.onreadystatechange = function() {
                        if (ajax.readyState == 4 && ajax.status == 200) {
                            resolve(ajax.responseText);
                        }
                    }
                    setTimeout(function() {
                        reject("请求服务器失败");
                    }, 1000)
                })
                
                return pro;
            }
            var pro = ajaxPromise("./txt/user.json");
            pro.then(function(msg) {
                console.log(JSON.parse(msg));
            }, function(msg) {
                console.log(msg);
            })

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM