他们说$ .each同步运行

时间:2017-09-09 08:56:13

标签: javascript jquery asynchronous promise

我有JQuery每个语句在对象数组上滚动,并检查该对象中的值是否为空,让用户使用bootbox在提示窗口中输入该值,然后继续循环直到完成。

每个语句完成后,ajax函数应该触发持有每个精炼的对象。

问题是ajax函数在每个语句运行时异步激活!

$.each(objs,function(k,v){

if (v == empty)
  //prompt bootbox modal to enter the value and (at this time ajax is fired
  v=bootboxpromptvalue   )

}) 
$.ajax({
..
...
....
data:objs
})  

问题是为什么ajax会在每个运行时触发,因为$ .each语句应该是同步的,之后的任何内容应该在它完成后运行?

1 个答案:

答案 0 :(得分:0)

bootbox提示是异步的,因此在提示用户之前,$.each循环将继续,$.ajax调用将会执行。

要解决此问题,您应该在想要提示用户答案时立即退出执行,只有在您有答案时才应该再次尝试:

function process() {
    var isEmpty = false;
    $.each(objs, function(k,v){
        isEmpty = v == empty;
        if (isEmpty) {
            bootbox.prompt("Enter value for " + k, function(answer) {
                objs[k] = answer;
                // Now we have an answer, try again.
                process();
            });
            return false; // break out of `each`
        }
    }
    // Exit if we asked for user input. There will be 
    // a new call to this function later.
    if (isEmpty) return;
    // We got everything now, so execute the request
    $.ajax({
        //...
        data: objs
    });
}
相关问题