【问题标题】:Why do functions execute when in array but dont when used with jquery 'when'为什么函数在数组中时执行,但在与 jquery 'when' 一起使用时不执行
【发布时间】: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


【解决方案1】:

而不是这个:

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);
    });
}

为了解决这个问题,我没有将一个已执行函数的数组传递给应用程序,而是使用 map 在应用程序中调用它们。它会执行类似的操作,但仅在实际调用 when 时。

这是一个小提琴:https://jsfiddle.net/bqpu2wdm/2/

【讨论】:

  • 我试过这个,但“何时”似乎没有正确执行。它输出:“所有 ajax 调用都已完成,现在可以进行数据组合。”但是,它似乎没有调用函数来输出:起始站点url查询:jsonplaceholder.typicode.com/posts/1起始站点url查询:jsonplaceholder.typicode.com/posts/2
  • 在什么时候试试这个:$.when(deferParams).then... 而不是使用 apply
  • 我也试过了,它仍然没有在控制台中产生任何东西。 jsfiddle.net/rezelute/5oq8jqqy
  • @Rezzy 我添加了一个带有 jsfiddle 的解决方案,看看并告诉我你的进展情况。
  • 谢谢 Rick,不过我看不出 jsfiddle 代码有什么不同。
猜你喜欢
  • 2016-04-20
  • 1970-01-01
  • 2021-07-12
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
相关资源
最近更新 更多