我试图将动态函数传递给“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;
})
}
}
我从上面得到的控制台日志发生一次(这是我所期望的):
起始站点url查询:https://jsonplaceholder.typicode.com/posts/1
起始站点url查询:https://jsonplaceholder.typicode.com/posts/2
如果我注释掉“when” block ,以便数组中的函数不再执行,我会在控制台中得到相同的输出,这意味着数组中的函数仍在执行。
为什么数组中的函数在使用“when”时执行一次,但在该 block 被注释掉时仍然执行?另外,如果有更好的方法来使用“何时”的动态函数,请告诉我。
谢谢。
最佳答案
而不是这个:
deferParams = [ajax1('1'), ajax1('2')];
这样做:
deferParams = [() => ajax1('1'), () => ajax1('2')];
在第一个例子中,当将它们传递到数组中时,您实际上是在执行函数
编辑:
为了完成这项工作,我对您的代码进行了一些重构:
function getPost(postNum) {
console.log('Calling with', postNum);
return ajaxCommon('https://jsonplaceholder.typicode.com' + '/posts/' + postNum);
}
function ajaxCommon(siteURL) {
console.log("starting site url query: ", siteURL);
return $.ajax({
url: siteURL,
method: 'GET'
});
}
function multiAjaxCalls() {
var numOfAjaxToCall = 2; //could be 1 or 2
var posts = [];
for (var i = 0; i < numOfAjaxToCall; i++) {
posts.push(i);
}
$.when.apply(null, posts.map(p => getPost(p)))
.then(function () {
console.log("all ajax calls have been completed, combination of data can happen now.");
var objects = arguments;
console.log(objects);
})
.fail(function(e) {
console.log('A call failed', e);
});
}
为了解决这个问题,我没有将已执行函数的数组传递给 apply,而是使用 map 在 apply 中调用它们。它会执行类似的操作,但仅在 when
实际被调用时才执行。
这是一个 fiddle :https://jsfiddle.net/bqpu2wdm/2/
关于javascript - 为什么函数在数组中执行但与 jquery 一起使用时不执行 'when',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48093642/