jquery 精巧的$.when 小记
[javascript]
// Deferred helper
when: function( object ) {
var args = arguments,
length = args.length,
deferred = length <= 1 && object && jQuery.isFunction( object.promise ) ?
object :
jQuery.Deferred(),
promise = deferred.promise(),
resolveArray;
if ( length > 1 ) {
resolveArray = new Array( length );
jQuery.each( args, function( index, element ) {
jQuery.when( element ).then( function( value ) {
resolveArray[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value;
if( ! --length ) {
deferred.resolveWith( promise, resolveArray );
}
}, deferred.reject );
} );
} else if ( deferred !== object ) {
deferred.resolve( object );
}
/*
分支#1: isResolve() = true length 递减
1: 默认如果没有返回promise,resolve触发,状态为isResolve() = true, length 递减 1
2:直接按返回romise,如果返回isResolve() = true, 执行then->done length 递减 1
分支#2: isReject()=true 执行then->fail
结果:递归最外层的deferred在跳出之前状态是isResolve() = false, isRejeced() = false
分支#2永远得不到执行的情况下,最终 isResolve() = true
如果分支#2被执行一次,分支#1中就少递减 1, isResolve() = false 就不会得到改变
因为只有每次都递减 1 最外层的 isResolve() = false 才能通过
deferred.resolveWith( promise, resolveArray );进行改变
最后 返回这个状态,供调用函数处理分支
*/
return promise;
},
[/javascript]