好的,我已经通过采用“何时”实现并创建自己的版本来解决它
$.extend({
when2: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = Array.prototype.slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? Array.prototype.slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
//.fail( deferred.reject )
// here is the modified line
.fail( updateFunc( i, resolveContexts, resolveValues ) )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.when2.apply(this, args)
.then(function(){
var combinedResults = {};
for (var i = 0; i < arguments.length; i++) {
var singleResult = arguments[i];
console.log(singleResult);
if(singleResult[1]==="success"){
for(var serviceName in singleResult[0]){
combinedResults[serviceName] = singleResult[0][serviceName];
}
}
}
console.log(combinedResults);
});
});
以这种方式,何时将始终完成所有结果传递给 then 的参数是数组,每个数组都包含树值,其中第二个是您可以确定调用成功或失败的状态
我已经将我的测试代码放在了 github 上,它有一个小的 nodejs 服务器,它返回不同的 http 状态代码用于测试目的。
https://github.com/szydan/test-jquery-defered