我的代码在' $.当block没有触发jQuery时

My code inside `$.when` block is not firing with jQuery

本文关键字:jQuery block 代码 我的      更新时间:2023-09-26

我试图在jQuery中使用$.when(some function).then(some function)来强制回调函数等待,直到$.when()中的代码首先完成。

这是我的功能。

function activateFirstTab(callback) {
    console.log('started activateFirstTab');
    console.log('Total groups found: '+ $('.functionParameterGroup').length);
    $.when(function () {
        $('.functionParameterGroup').each(function () {
            //Activate the first tab "which is the default"
            var first = $(this).find('ul > li:first');
            first.addClass('active');
            var contentId = first.data('contentid');
            $(contentId).addClass('in active');
            console.log('finished when logic in activateFirstTab');
        });
    }).then(function () {
        // Make sure the callback is a function​
        if (typeof callback === "function") {
            // Call it, since we have confirmed it is callable​
            callback();
        }
    });

    console.log('finished activateFirstTab');
}
在控制台中,我得到以下消息
started activateFirstTab
Total groups found: 2
finished activateFirstTab

但是我从来没有从$.when()

里面的块中得到消息

我期望输出是这样的

started activateFirstTab
Total groups found: 2
finished when logic in activateFirstTab
finished when logic in activateFirstTab
finished activateFirstTab

为什么$.when()里面的代码没有被执行?

我如何让它执行它?我犯了什么错误?

你不调用$.when()内的函数,也注意传递给$.when()的匿名函数不返回承诺;尽管任何类型的参数都可以传递给$.when()

function fn(callback) {
  $.when(function dfd(callback) {
      $.each([1, 2, 3], function(i, value) {
        console.log(value)
      });
      return "dfd complete"
    }() /* invoke `dfd` function */ )
    .then(function(data) {
      // Make sure the callback is a function​
      if (typeof callback === "function") {
        // Call it, since we have confirmed it is callable​
        callback(data);
      }
    })
}
fn(function(args) {
  alert(args)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>