2016-10-28 4 views
1

나는 함수에 약속을 추가하려고 했으므로 함수가 먼저 완료 될 때까지 기다릴 것이다. $.when.promise()을 시도하고 .map 함수가 완료 될 때 변경되는 변수 및 카운터를 추가했지만 if 문 앞에 및 inputTNACheck의 값을 완료하고 변경하기 위해 checkInput() 함수를 가져올 수 없습니다. 실행합니다. 이 때문에 심지어 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 
     }); 
    } 

답변

0

우선 몇 가지 기본 ...

내가 너무 완료 및

x이 이벤트 핸들러에 정의 된 x의 값을 변경할 수 checkInput() 함수를 얻을 수 없다 checkInputs()이라고해도 이벤트 핸들러에서을 호출해도 이벤트 핸들러 범위에서 정의 된 변수에 액세스 할 수는 없습니다 ss는 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. 
}); 

희망은 올바른 방향으로이 작은 밀쳐은

을하는 데 도움이
관련 문제