上一篇文章"JQuery.deferred提供的promise解决方式",提到了javascript异步操作的3个问题,以及javascript Promise入门。如今我们看下怎样利用$.when()来解决上一篇博客中的第3个问题。

“考虑这样的场景。假如我们同一时候发送两个Ajax请求,然后要在两个请求都成功返回后再做一件接下来的事,想一想假设仅仅按前面的方式在各自的调用位置去附加回调,这是不是非常困难?”

使用when(),我们能够通过类似以下的代码解决问题。

以下这段代码能够实现这个效果:当ajax1和ajax2操作都成功的时候。会调用onDone回调函数。

var promise1 = $.ajax(url1),
promise2 = $.ajax(url2),
promiseCombined = $.when(promise1, promise2);
promiseCombined.done(onDone);

$.when()方法能够合并多个Promise得到一个新的Promise,相当于在原多个Promise之间建立了AND(逻辑与)的关系。假设全部组成Promise都已成功,则令合并后的Promise也成功。假设有随意一个组成Promise失败,则马上令合并后的Promise失败。

1.$.when()不传參数,或者參数既不是Deferred对象也不是Promise对象。

这样的场景没有什么实际作用。

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. The doneCallbacks are passed the original
argument. In this case any failCallbacks you might set are never called since the Deferred is never rejected. For example:

$.when( { testing: 123 } ).done(function( x ) {
alert( x.testing ); // Alerts "123" immediately
});

If you don't pass it any arguments at all, jQuery.when() will return a resolved promise.

$.when().done(function( x ) {
alert( "I fired immediately" );//x is undefined
});

2.$.when()仅仅有1个參数。该參数是Deferred或者Promise对象。

If a single Deferred is passed to jQuery.when(), its Promise object (a subset of the Deferred methods) is returned by the method. Additional methods of the Promise object can be called to attach callbacks, such as deferred.done.
When the Deferred is resolved or rejected, usually by the code that created the Deferred originally, the appropriate callbacks will be called. For example, the jqXHR object returned by jQuery.ajax() is a Promise-compatible object and can be used this way:

$.when( $.ajax( "test.aspx" ) ).done(function( data, textStatus, jqXHR ) {
alert( jqXHR.status ); // Alerts 200
});
// 创建1个延迟对象
var dtd = $.Deferred(); // 返回这个延迟对象的Promise
var its_promise = $.when(dtd); // 能够利用promise绑定各种回调函数
its_promise.done(function(){alert("success");}); // 改变状态仅仅能通过Deferred对象
dtd.resolve();

3.$.when()參数是多个Deferred或者Promise对象。这样的场景才是when()真正的价值所在。

In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will
resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, the doneCallbacks for the master Deferred are executed. The arguments passed to
the doneCallbacks provide the resolved values for each of the Deferreds, and matches the order the Deferreds were passed to jQuery.when(). For example:

var d1 = $.Deferred();
var d2 = $.Deferred(); $.when( d1, d2 ).done(function ( v1, v2 ) {
console.log( v1 ); // "Fish"
console.log( v2 ); // "Pizza"
}); d1.resolve( "Fish" );
d2.resolve( "Pizza" );

这就是相当于2个Promise进行逻辑与操作,得到1个新的Promise。

In the event a Deferred was resolved with no value, the corresponding doneCallback argument will be undefined. If a Deferred resolved to a single value, the corresponding argument will hold that value. In the case where a Deferred
resolved to multiple values, the corresponding argument will be an array of those values. For example:

var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred(); $.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
console.log( v1 ); // v1 is undefined
console.log( v2 ); // v2 is "abc"
console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
}); d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 );

使用$.when()解决AJAX异步难题之:多个ajax操作进行逻辑与(and)的更多相关文章

  1. 【坑】前端使用ajax异步请求以后,springMvc拦截器跳转页面无效

    文章目录 前言 `$.ajaxSetup( )` 后记 前言 本文着重解决前后端分离开发的页面调整问题. 笔者,在做一个需求,需要对访问网站,但是没有登录的用户进行拦截,将他们重定向到首页. 很简单的 ...

  2. 项目中使用的ajax异步读取数据结构设计

    设计稍微复杂了一点,完成ajax读取功能涉及到了很多页面.虽然如此,但感觉比较灵活. 和传统方法唯一的区别在于多了一层数据容器控件,里面提供了显示数据的HTML元素及相应的JS方法. 这样数据控件指生 ...

  3. ajax异步服务器获取时间

    1.创建ajax对象 <script type="text/javascript"> //创建AJAX异步对象 function createAJAX(){ var a ...

  4. ajax异步请求302分析

    1.前言 遇到这样一种情况,打开网页两个窗口a,b(都是已经登录授权的),在a页面中退出登录,然后在b页面执行增删改查,这个时候因为授权原因,b页面后端的请求肯定出现异常(对这个异常的处理,进行内部跳 ...

  5. 关于AJAX异步加载节点无法触发点击事件问题的解决方式

    做练习的过程中遇到一个问题,使用AJAX异步新增一个节点,无法触发点击事件,经过查阅之后知道一个方式,使用JS的委托事件,在此做一个记录. $(document).on('click', '.recr ...

  6. 淘宝购物车页面 智能搜索框Ajax异步加载数据

    如果有朋友对本篇文章的一些知识点不了解的话,可以先阅读此篇文章.在这篇文章中,我大概介绍了一下构建淘宝购物车页面需要的基础知识. 这篇文章主要探讨的是智能搜索框Ajax异步加载数据.jQuery的社区 ...

  7. spring HandlerInterceptorAdapter拦截ajax异步请求,报错ERR_INCOMPLETE_CHUNKED_ENCODING

    话不多说,直接上正文. 异常信息: Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING 问题描述: 该异常是在页面发送ajax请 ...

  8. jquery Ajax异步请求之session

    写了一个脚本,如下: $(function () { $("#btnVcode").click(function () { var receiveMobile = $(" ...

  9. 触碰jQuery:AJAX异步详解

    触碰jQuery:AJAX异步详解 传送门:异步编程系列目录…… 示例源码:触碰jQuery:AJAX异步详解.rar AJAX 全称 Asynchronous JavaScript and XML( ...

随机推荐

  1. Cookie测试的测试点

    1.禁止使用Cookie:设置浏览器禁止使用Cookie,访问网页后,检查存放Cookie文件中未生成相关文件: 2.Cookie寻出路径:按照操作系统和浏览器对Cookie存放路径的设置,检查存放路 ...

  2. 字符串格式化format很牛B

    python的format方法可谓相当强大,它可以接受不限个参数... 1.通过位置来格式化字符串,注意format传入的参数的位置要正确{0}对应第1个参数,{1}对应第2个参数... >&g ...

  3. 【Luogu】P1410子序列(DP)

    题目链接 我DP是真的菜啊啊啊啊啊! f[i][j]表示考虑前i个数,有i-j+1个数组成一个上升子序列,且不以i结尾的尾端最小值. 设a为j个数组成的序列,且以i结尾:b为i-j+1个数组成的序列, ...

  4. BZOJ2561 最小生成树 【最小割】

    题目 给定一个边带正权的连通无向图G=(V,E),其中N=|V|,M=|E|,N个点从1到N依次编号,给定三个正整数u,v,和L (u≠v),假设现在加入一条边权为L的边(u,v),那么需要删掉最少多 ...

  5. 如何解决maven archetype加载太慢的方法

    有时候在构建maven项目时,archetype加载不出来,一直在Retrieving archetype...,现象如下: 有两种解决方法: ①点击链接下载:http://files.cnblogs ...

  6. kubernetes---CentOS7安装kubernetes1.11.2图文完整版

    转载请注明出处:kubernetes-CentOS7安装kubernetes1.11.2图文完整版 架构规划 k8s至少需要一个master和一个node才能组成一个可用集群. 本章我们搭建一个mas ...

  7. *Codeforces989D. A Shade of Moonlight

    数轴上$n \leq 100000$个不重叠的云,给坐标,长度都是$l$,有些云速度1,有些云速度-1,风速记为$w$,问在风速不大于$w_{max}$时,有几对云可能在0相遇.每一对云单独考虑. 多 ...

  8. Java面试题集(四)

    二. Java Web基础部分 在js中如何创建一个对象? var p1={name:”tom”,”age”:12}; function Person(name,age){ this.name=nam ...

  9. 在dedecms系统下, 改写火车头的入库接口 写一个接口文件运行一次自动读取 http://news.163.com/rank/

    1:火车头入库接口里面的密码与login.php传过来的密码是保持一致的: 2:在(!$ispost)里面编写一个form表单提交,验证用户名,channelid,以及typeid; html代码格式 ...

  10. Android Service服务-(转)

    Service是Android系统中提供的四大组件之一.它是运行在后台的一种服务,一般声明周期较长,不直接与用户进行交互.   服务不能自己运行,需要通过调用Context.startService( ...