Javascript 将承诺约束到函数

Javascript 将承诺约束到函数,javascript,jquery,callback,promise,jquery-callback,Javascript,Jquery,Callback,Promise,Jquery Callback,我一直在尝试向函数添加一个承诺,这样它会等待函数首先完成。我尝试了$.when和.promise()以及添加一个计数器和一个变量,该变量在.map函数完成时更改,但我无法让checkInput()函数完成并在if语句执行之前更改x、inputSmartCheck和inputnacheck的值。因此,即使当checkInput()将x的值更改为1时,if语句也会在此之前执行并返回true。我对Javascript(我更喜欢jQuery)有点经验,但我认为我正在进入高级领域。任何帮助都将不胜感激

我一直在尝试向函数添加一个承诺,这样它会等待函数首先完成。我尝试了
$.when
.promise()
以及添加一个计数器和一个变量,该变量在.map函数完成时更改,但我无法让
checkInput()
函数完成并在if语句执行之前更改x、
inputSmartCheck
inputnacheck
的值。因此,即使当
checkInput()
将x的值更改为1时,if语句也会在此之前执行并返回true。我对
Javascript
(我更喜欢
jQuery
)有点经验,但我认为我正在进入高级领域。任何帮助都将不胜感激

        $(document).on("click", ".updateNewRows", function(){
        $("#inputTNACheck").val("0");  //hidden inputs
        $("#inputSmartCheck").val("0"); //hidden inputs
        var x=0;
        checkInput();
        if(x==0 && $("#inputTNACheck").val()=="0" && $("#inputSmartCheck").val()=="0"){
            $(".newStart").each(function () {
                var get = $(this).closest(".newStart");
                var data = {
                    empID:get.find(".tna_id").val(),
                    smart:get.find(".smart_uname").val(),
                    first:get.find(".f_name").val(),
                    last:get.find(".l_name").val(),
                    date:get.find(".start_date").val(),
                    type:get.find(".type").val()
                };
                $.post('new_user_process_bulk_create_records.php', data, function(data,textStatus) {
                    console.log(textStatus);
                    $("#newUsersTable").remove();
                    $(".updateNewRows").remove();
                    if ($("#returnUsersTable").html()) {
                        $("#newUsersRow").html('<div class="alert alert-success">Updated</div>');
                    }
                    else{
                        location.reload();
                    }

                });
            });
        }   
    });



  function checkInput(){
        $('.newStart').map(function () {    

            var get = $(this).closest(".newStart");

            var id = get.find(".tna_id");
            var smart = get.find(".smart_uname");
            var first = get.find(".f_name");
            var last = get.find(".l_name");
            var type = get.find(".type");
            var smartCheck = $.ajax({
                url: "new_user_validate_bulk_upload.php",
                type: "POST",
                data: {smart:smart.val(), type:'smart'},
                success: function(data) {
                    if(data!="ok"){
                        $("#inputSmartCheck").val("1");
                        smart.css('background-color', 'pink');
                    }
                    else{smart.css('background-color', 'white');}
                }
            });

            var tnaCheck = $.ajax({
                url: "new_user_validate_bulk_upload.php",
                type: "POST",
                data: {tna:id.val(), type:'tna'},
                success: function(data) {
                    if(data!="ok"){
                        $("#inputTNACheck").val("1");
                        id.css('background-color', 'pink');
                    }
                    else{id.css('background-color', 'white');}
                }
            });
            $.when(smartCheck, tnaCheck).then(function() {  

                var name = new RegExp('^[a-zA-Z-]{0,20}$');
                var smartID = new RegExp('^[a-zA-Z0-9]{0,10}$');
                var empID = new RegExp('^[0-9]{0,10}$');

                if (!name.test(first.val()) || first.val()=='') {
                    x=1;
                    first.css('border', '1px solid red');
                }else{first.css('border', '1px solid #CCC');}

                if (!name.test(last.val()) || last.val()=='') {
                    x=1;
                    last.css('border', '1px solid red');
                }else{last.css('border', '1px solid #CCC');}

                if(!smartID.test(smart.val()) || smart.val()==''){
                    x=1;
                    smart.css('border', '1px solid red');
                }else{smart.css('border', '1px solid #CCC');}

                if(!empID.test(id.val()) || id.val()==''){
                    x=1;
                    id.css('border', '1px solid red');
                }else{id.css('border', '1px solid #CCC');}

                if(type.val()==''){
                    x=1;
                    type.css('border', '1px solid red');
                }else{type.css('border', '1px solid #CCC');}
            });//$.when close
        });
    }
$(文档).on(“单击“,”.updateNewRows”,函数(){
$(“#InputNaCheck”).val(“0”);//隐藏的输入
$(“#inputSmartCheck”).val(“0”);//隐藏的输入
var x=0;
checkInput();
如果(x==0&&$(“#InputNaCheck”).val()==0&&$(“#inputSmartCheck”).val()==0”){
$(“.newStart”)。每个(函数(){
var get=$(this.nexist(“.newStart”);
风险值数据={
empID:get.find(“.tna_id”).val(),
smart:get.find(“.smart_uname”).val(),
首先:get.find(“.f_name”).val(),
last:get.find(“.l_name”).val(),
日期:get.find(“.start_date”).val(),
类型:get.find(“.type”).val()
};
$.post('new\u user\u process\u bulk\u create\u records.php',数据,函数(数据,文本状态){
console.log(textStatus);
$(“#newUsersTable”).remove();
$(“.updateNewRows”).remove();
if($(“#returnUsersTable”).html(){
$(“#newUsersRow”).html('Updated');
}
否则{
location.reload();
}
});
});
}   
});
函数checkInput(){
$('.newStart').map(函数(){
var get=$(this.nexist(“.newStart”);
var id=get.find(“.tna_id”);
var smart=get.find(“.smart_uname”);
var first=get.find(“.f_name”);
var last=get.find(“.l_name”);
var type=get.find(“.type”);
var smartCheck=$.ajax({
url:“新用户验证批量上传.php”,
类型:“POST”,
数据:{smart:smart.val(),类型:'smart'},
成功:功能(数据){
如果(数据!=“正常”){
$(“#inputSmartCheck”).val(“1”);
css('background-color','pink');
}
else{smart.css('background-color','white');}
}
});
var tnaCheck=$.ajax({
url:“新用户验证批量上传.php”,
类型:“POST”,
数据:{tna:id.val(),类型:'tna'},
成功:功能(数据){
如果(数据!=“正常”){
$(“#输入检查”).val(“1”);
id.css('background-color','pink');
}
else{id.css('background-color','white');}
}
});
$.when(smartCheck,tnaCheck).then(function(){
var name=newregexp('^[a-zA-Z-]{0,20}$');
var smartID=newregexp('^[a-zA-Z0-9]{0,10}$');
var empID=newregexp('^[0-9]{0,10}$');
如果(!name.test(first.val())| | first.val()=''){
x=1;
css('border','1px实心红色');
}else{first.css('border','1px solid#CCC');}
如果(!name.test(last.val())| | last.val()=''){
x=1;
css('border','1px实心红色');
}else{last.css('border','1px solid#CCC');}
如果(!smartID.test(smart.val())| | smart.val()=''){
x=1;
css('border','1px实心红色');
}else{smart.css('border','1px solid#CCC');}
如果(!empID.test(id.val())| | id.val()=''){
x=1;
id.css('border','1px实心红色');
}else{id.css('border','1px solid#CCC');}
如果(type.val()=''){
x=1;
type.css('border','1px实心红色');
}else{type.css('border','1px solid#CCC');}
});//$。关闭时
});
}
首先介绍一些基本知识

我无法使checkInput()函数完成并更改x的值

x
在事件处理程序中定义,因此当您在
checkInputs()
中引用它时,即使它在事件处理程序中被调用,它也无权访问在事件处理程序范围内定义的变量,除非
checkInputs
函数也在该事件处理程序中定义。(我不建议在这种情况下,这意味着每次事件处理程序运行时都要创建一个函数,这没什么大不了的,但仍然是不必要的。)

在执行if语句之前

因为
checkInputs()
执行异步操作,所以您不能仅仅依靠调用它而不通过某种方式来确定它是否完成了。好消息是你在正确的轨道上做出了承诺

按照
checkInputs
目前的工作方式,您永远不会知道在
if
语句之前是否完成了所有异步操作。让我们用一些基于
checkInputs
函数的示例代码来解决这个问题

function checkInputs() {
    // an array to store the async calls
    var asyncCalls = [];

    // iterate over all the things
    // changed to .each() because "each" is for iterating, 
    // and "map" is for returning a new array
    $('.newStart').each(function() {
        // get all your variables and stuff
        var smartCheck = $.ajax({...});

        var tnaCheck = $.ajax({...});

        var asyncCallsPromise = $.when(smartCheck, tnaCheck).then(function() {
            // do stuff

            console.log(arguments);
        });
        asyncCalls.push(asyncCallsPromise);
    });

    // the important part, return a promise so you can check 
    // when checkInputs has processed all the things
    return $.when.apply($, asyncCalls);
}

// somewhere else...
checkInputs().then(function() {
  console.log('all the calls are done');
  // here you can do the things that need to happen after checking the inputs
  // e.g. the if statement.
});
希望这一点对正确的方向有所帮助

首先是一些基础知识

我无法完成checkInput()函数