用Promise解决多个异步Ajax请求导致的代码嵌套问题(完美解决方案)
前端  /  管理员 发布于 4年前   211
问题
前端小同学在做页面的时候,犯了个常见的错误:把多个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), 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请求的代码重复很严重
思路
//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三个必要的参数要填,其他都定死了
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的方案
解决方案
其实现代浏览器都已经内置支持了Promise,连第三方库都不需要了,只有IE不行,放弃了
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)
以上所述是小编给大家介绍的用Promise解决多个异步Ajax请求导致的代码嵌套问题(完美解决方案),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号