使用 jQuery 3.0.0,给定
$(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>
第一次调用jQueryWhenApplyResolveRejectWith
应该返回一个已解析的 jQuery 承诺值数组,位于.then()
chained to promises
,其中this
是一个obj
对象数组。
第二次调用jQueryWhenApplyResolveRejectWith
应该返回Error
,并this
设置为单个对象obj
。
的预期结果success
设置this
为 single obj
,因为单个对象被传递给deferred.resolveWith
.
虽然没有返回预期的结果,但javascript
在 stacksnippets 处,可以通过 using.bind()
或$.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>
问题:
为什么
this
从传递给的普通对象转换为数组.resolveWith()
;而传递给的同.rejectWith()
一个对象使用模式返回一个对象$.when.apply()
?在同一过程中使用
$.when.apply()
or 或两者的预期行为是否设置为包含原始数组乘以已解析的 jQuery 承诺对象的数量?.resolveWith()
this
this