用Promise解决多个异步Ajax请求导致的代码嵌套问题
问题前端小同学在做页面的时候,犯了个常见的错误:把多个Ajax请求顺序着写下来了,而后面的请求,对前面请求的返回结果,是有依赖的。如下面的代码所示: 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),success: function (resp) { //do something on response },errorThrown) { //在这个页面里,所有的请求的错误都做同样的处理 if (XMLHttpRequest.status == "401") { window.location.href = '/login.html'; } else { alert(XMLHttpRequest.responseText); } } }); 以上代码有两个问题: 思路
//url:地址 //data:数据对象,在函数内部会转化成json串,如果没传,表示用GET方法,如果传了,表示用POST方法 function ajax(url,data,callback) { $.ajax({ url: url,type: data == null ? 'GET' : 'POST',data: data == null ? '' : JSON.stringify(data),success: function (resp) { callback(resp); },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三个必要的参数要填,其他都定死了
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 } }; 至此问题似乎解决得很完美,但可以想见,如果请求不止两个,而是4、5个,同时还有其他异步操作(比如我们的页面里有Vue对象的初始化),相互之间有依赖关系,光是这样层层叠叠的括号嵌套,就已经让人头晕了。 需要找到一种方法,让异步调用的表达看起来像同步调用一样。 正好最近看了阮一峰老师关于ES6的书,而且用户也没有强硬要求兼容IE浏览器,于是就选择了Promise的方案 解决方案
function ajax(url,callback) { var p = new Promise(function (resolve,reject) { $.ajax({ url: url,success: function (resp) { callback(resp); resolve(); },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',function(resp){ //do something on response someData.attr1 = resp.attr1; }).then( ajax('/prefix/entity2/action2',function(resp){ //do something on response } ).then( initVue() ; ).then( //do something else ) 至此完美解决。 经@miroki 提醒,发现Jquery从1.5版开始,返回的就是thenable对象了,那么ajax函数可以直接返回$.ajax()的返回值 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |