jQuery"each()"函数是否同步?

Sae*_*ati 125 jquery asynchronous

考虑这种情况进行验证:

function validateForm (validCallback) {
   $('#first-name').add($('#last-name')).add($('#address')).each(function () {
      // validating fields and adding 'invalid' class to invalid fields.
   });
   // doing validation this way for almost 50 fields (loop over 50 fields)
   if ($('#holder .invalid').length == 0) {
       // submitting data here, only when all fields are validated.
   }
}
Run Code Online (Sandbox Code Playgroud)

现在,我的问题是,if块在循环完成之前执行.我期望validateForm同步执行主体,但似乎each()异步执行jQuery 函数.我对吗?为什么这不起作用?

Abr*_*ham 150

是的,jQuery each方法是同步的.几乎所有JavaScript都是同步的.唯一的例外是AJAX,计时器(setTimeoutsetInterval)以及HTML5 Web Workers.
您的问题可能在您的代码中的其他位置.


Sha*_*oli 7

jQuery纯粹是一个JavaScript库.除此之外ajax,setTimeoutsetInterval没有什么可以在异步执行JavaScript.所以each肯定是同步执行的.each块代码中肯定存在一些js错误.您应该在控制台中查看是否存在任何错误.

或者,您可以查看jQuery 队列以执行队列中的任何功能.这将确保仅在前一代码执行完成时才执行排队功能.

  • there are also promises... just saying :) (7认同)

Mor*_*rg. 5

提出该问题的另一个原因是,当(.each())函数返回false时,.each将仅停止迭代,并且必须使用附加变量来传递“ return false”信息。

var all_ok=true;
$(selector).each(function(){
    if(!validate($(this))){
        all_ok=false; //this tells the outside world something went wrong
        return false; //this breaks the .each iterations, returning early
    }
});
if(!all_ok){
    alert('something went wrong');
}
Run Code Online (Sandbox Code Playgroud)


小智 5

对我来说,它的工作原理就像异步的。如果它可以同步,为什么它会这样工作:

var newArray = [];
$.each( oldArray, function (index, value){
        if($.inArray(value["field"], field) === -1){
            newArray.push(value["field"]);
        }
    }
);

//do something with newArray here doesn't work, newArray is not full yet

$.when.apply($, newArray).then(function() {
    //do something with newArray works!! here is full
});
Run Code Online (Sandbox Code Playgroud)