【发布时间】:2018-06-14 02:06:22
【问题描述】:
我正在尝试将动态函数传递给“when”语句,但是当“when”被注释掉时,函数仍然会从数组中调用。
multiAjaxCalls();
function multiAjaxCalls()
{
var deferParams = [];
var numOfAjaxToCall = 2; //could be 1 or 2
if (numOfAjaxToCall === 1) {
deferParams = [ajax1('1')];
}
else if (numOfAjaxToCall === 2) {
deferParams = [ajax1('1'), ajax1('2')];
}
//If this is commented out then the function(s) in the array above still execute
//If this is NOT commented out, the function only executes once
$.when.apply($, deferparams).then(
function () {
console.log("all ajax calls have been completed, combination of data can happen now.");
var objects = arguments;
console.log(objects);
},
function (event) {
console.log("failed in when ", event);
}
);
function ajax1(posnum)
{
return ajaxCommon('https://jsonplaceholder.typicode.com' + '/posts/' + posnum);
}
function ajax2(posnum)
{
return ajaxCommon('https://jsonplaceholder.typicode.com' + '/posts/' + posnum);
}
function ajaxCommon(siteURL)
{
console.log("starting site url query: ", siteURL);
return $.ajax({
url: siteURL,
method: 'GET'
})
.done(function (data)
{
//console.log("DONE", data);
return data;
})
.fail(function (data)
{
//console.log("failed INSIDE AJAX URL:", siteURL, "Data: " , data);
return data;
})
}
}
我从上面得到的控制台日志发生一次(这是我所期望的):
起始网址查询:https://jsonplaceholder.typicode.com/posts/1
起始网址查询:https://jsonplaceholder.typicode.com/posts/2
如果我注释掉“when”块,以使数组中的所有函数都不再执行,我会在控制台中得到相同的输出,这意味着数组中的函数仍在执行。
为什么数组中的函数在使用'when'时执行一次,但在注释掉该块时仍然执行?另外,如果有更好的方式使用“何时”处理动态函数,请告诉我。
谢谢。
【问题讨论】:
-
那么为什么在使用'when'块时它们没有被调用两次呢?防止它们在数组中被调用同时仍然能够在“何时”执行它们的最佳方法是什么?
标签: javascript jquery arrays .when