Using jQuery 3.0.0, given
$(function() {
var n = 5;
function jQueryWhenApplyResolveRejectWith(n) {
var arr = $.map(Array(5), function(_, i) {
return $.Deferred();
});
var obj = {
"index": null
};
var promises = $.when.apply(null, arr.map(function(promise, i) {
return i < n
? promise.resolveWith(obj, [i])
: promise.rejectWith((obj.index = i, obj)
, [new Error(i + " is not less than " + n)])
}));
function success(...result) {
console.log("resolved, result:", result, "this:", this);
}
function err(error) {
console.log("rejected, error:", error, "this:", this);
}
return promises.then(success, err);
}
jQueryWhenApplyResolveRejectWith(n)
.then($.proxy(jQueryWhenApplyResolveRejectWith, null, --n))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js">
</script>
the first call to jQueryWhenApplyResolveRejectWith
should return an array of resolved jQuery promise values at .then()
chained to promises
, where this
is an array of obj
objects.
The second call to jQueryWhenApplyResolveRejectWith
should return Error
, with this
set to single object obj
.
The expected result of success
is this
set to single obj
, as single object was passed to deferred.resolveWith
.
Though the expected result is not returned, at javascript
at stacksnippets, the single object can be returned by using .bind()
or $.proxy()
at .then()
chained to promises
.
$(function() {
var n = 5;
function jQueryWhenApplyResolveRejectWith(n) {
var arr = $.map(Array(5), function(_, i) {
return $.Deferred();
});
var obj = {
"index": null
};
var promises = $.when.apply(null, arr.map(function(promise, i) {
return i < n
? promise.resolveWith(obj, [i])
: promise.rejectWith((obj.index = i, obj)
, [new Error(i + " is not less than " + n)])
}));
function success(...result) {
console.log("resolved, result:", result, "this:", this);
}
function err(error) {
console.log("rejected, error:", error, "this:", this);
}
return promises.then($.proxy(success, obj), err);
}
jQueryWhenApplyResolveRejectWith(n)
.then($.proxy(jQueryWhenApplyResolveRejectWith, null, --n))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js">
</script>
Questions:
Why is
this
converted to an array from the plain object passed to.resolveWith()
; while the same object passed to.rejectWith()
returns a single object using$.when.apply()
pattern?Is the expected behaviour of using
$.when.apply()
or.resolveWith()
, or both in same procedure,this
being set to an array containing originalthis
multiplied by the number of resolved jQuery promise objects?