前端小同窗在作页面的时候,犯了个常见的错误:把多个Ajax请求顺序着写下来了,然后面的请求,对前面请求的返回结果,是有依赖的。以下面的代码所示:html
var someData; $.ajax({ url: '/prefix/entity1/action1', type: 'GET' , async: true, contentType: "application/json", success: function (resp) { //do something on response someData.attr1 = resp.attr1; }, error: function (XMLHttpRequest, textStatus, errorThrown) { //在这个页面里,全部的请求的错误都作一样的处理 if (XMLHttpRequest.status == "401") { window.location.href = '/login.html'; } else { alert(XMLHttpRequest.responseText); } } }); $.ajax({ url: '/prefix/entity2/action2', type: 'POST' , dataType: "json", data: JSON.stringify(someData), async: true, contentType: "application/json", success: function (resp) { //do something on response }, error: function (XMLHttpRequest, textStatus, errorThrown) { //在这个页面里,全部的请求的错误都作一样的处理 if (XMLHttpRequest.status == "401") { window.location.href = '/login.html'; } else { alert(XMLHttpRequest.responseText); } } });
以上代码有两个问题:
*首先就是执行顺序不能保证,action2极可能在action1返回以前就发出了,致使someData.attr1这个参数没能正确传出
*其次两个ajax请求的代码重复很严重前端
代码重复的问题相对好解决,尤为是在本身的项目里,各类参数能够经过规范定死,封装一个参数更少的ajax方法就行了ajax
//url:地址 //data:数据对象,在函数内部会转化成json串,若是没传,表示用GET方法,若是传了,表示用POST方法 function ajax(url, data, callback) { $.ajax({ url: url, type: data == null ? 'GET' : 'POST', dataType: "json", data: data == null ? '' : JSON.stringify(data), async: true, contentType: "application/json", success: function (resp) { callback(resp); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (XMLHttpRequest.status == "401") { window.parent.location = '/enterprise/enterprise_login.html'; self.location = '/enterprise/enterprise_login.html'; } else { alert(XMLHttpRequest.responseText); } } }); }
这样只有url,data和callback三个必要的参数要填,其余都定死了json
执行顺序的问题,能够把第二个请求放在第一个请求的回调里,形如:浏览器
ajax('/prefix/entity1/action1',null, function(resp){ //do something on response someData.attr1 = resp.attr1; ajax('/prefix/entity2/action2', someData, function(resp){ //do something on response } };
至此问题彷佛解决得很完美,但能够想见,若是请求不止两个,而是四、5个,同时还有其余异步操做(好比咱们的页面里有Vue对象的初始化),相互之间有依赖关系,光是这样层层叠叠的括号嵌套,就已经让人头晕了。app
须要找到一种方法,让异步调用的表达看起来像同步调用同样。异步
正好最近看了阮一峰老师关于ES6的书,并且用户也没有强硬要求兼容IE浏览器,因而就选择了Promise的方案async
引入Promise
其实现代浏览器都已经内置支持了Promise,连第三方库都不须要了,只有IE不行,放弃了函数
改造ajax封装函数,在成功的时候调用resolve(),失败的时候调用reject(),而且返回Promise对象url
function ajax(url, data, callback) { var p = new Promise(function (resolve, reject) { $.ajax({ url: url, type: data == null ? 'GET' : 'POST', dataType: "json", data: data == null ? '' : JSON.stringify(data), async: true, contentType: "application/json", success: function (resp) { callback(resp); resolve(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (XMLHttpRequest.status == "401") { window.parent.location = '/enterprise/enterprise_login.html'; self.location = '/enterprise/enterprise_login.html'; } else { alert(XMLHttpRequest.responseText); } reject(); } }); }); return p; }
修改调用端
ajax('/prefix/entity1/action1',null, function(resp){ //do something on response someData.attr1 = resp.attr1; }).then( ajax('/prefix/entity2/action2', someData, function(resp){ //do something on response } ).then( initVue() ; ).then( //do something else )
至此完美解决。
经@miroki 提醒,发现Jquery从1.5版开始,返回的就是thenable对象了,那么ajax函数能够直接返回$.ajax()的返回值