programing

이전 기능이 완료된 후 함수를 호출합니다.

randomtip 2022. 9. 14. 22:05
반응형

이전 기능이 완료된 후 함수를 호출합니다.

다음 JavaScript 코드가 있습니다.

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable);
        function2(someOtherVariable);
    }
    else {
        doThis(someVariable);
    }
});

어떻게 해야 할까요?function2다음에 호출됩니다.function1완료되었습니까?

어나니머스 콜백을 지정하고 function1에서 이를 받아들이도록 합니다.

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});


function function1(param, callback) {
  ...do stuff
  callback();
} 

jQuery 1.5를 사용하는 경우 새로운 지연 패턴을 사용할 수 있습니다.

$('a.button').click(function(){
    if(condition == 'true'){
        $.when(function1()).then(function2());
    }
    else {
        doThis(someVariable);
    }
});

편집: 업데이트된 블로그 링크:

Rebecca Murphy는 이 점에 대해 http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/에 훌륭한 글을 남겼다.

다음을 시도해 보십시오.

function method1(){
   // some code

}

function method2(){
   // some code
}

$.ajax({
   url:method1(),
   success:function(){
   method2();
}
})

이 답변에서는 의 JavaScript 기능인 를 사용합니다.ECMAScript 6표준.타겟 플랫폼이 다음을 지원하지 않는 경우promises, PromiseJs로 폴리필합니다.

약속은 JavaScript에서 비동기 작업을 처리하는 새로운(그리고 훨씬 더 나은) 방법입니다.

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable).then(function() {
            //this function is executed after function1
            function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});


function function1(param, callback) {
    return new Promise(function (fulfill, reject){
        //do stuff
        fulfill(result); //if the action succeeded
        reject(error); //if the action did not succeed
    });
} 

이 간단한 예에서는 상당한 오버헤드로 보일 수 있지만 복잡한 코드에서는 콜백을 사용하는 것보다 훨씬 좋습니다.여러 개의 비동기 콜을 사용하여 쉽게 여러 개의 비동기 콜을 연결할 수 있습니다.then스테이트먼트:

function1(someVariable).then(function() {
    function2(someOtherVariable);
}).then(function() {
    function3();
});

jQuery deferds를 쉽게 래핑할 수도 있습니다(이러한 지연은 에서 반환됩니다).$.ajax콜) :

Promise.resolve($.ajax(...params...)).then(function(result) {
    //whatever you want to do after the request
});

@charlietfl에서 설명한 바와 같이jqXHR에 의해 반환된 오브젝트$.ajax()를 실장하다Promise인터페이스입니다.그래서 실제로 그것을 포장할 필요는 없습니다.Promise, 직접 사용할 수 있습니다.

$.ajax(...params...).then(function(result) {
    //whatever you want to do after the request
});

또는 하나의 기능이 완료될 때 사용자 정의 이벤트를 트리거한 후 문서에 바인딩할 수 있습니다.

function a() {
    // first function code here
    $(document).trigger('function_a_complete');
}

function b() {
    // second function code here
}

$(document).bind('function_a_complete', b);

이 방법을 사용하면 함수 a의 실행이 종료되었을 때만 트리거가 존재하므로 함수 'b'는 AFTER 함수 'a'만 실행할 수 있다.

이렇게 하면 된다

$.when(funtion1()).then(function(){
    funtion2();
})

이것은 기능 1이 무엇을 하고 있는지에 따라 달라집니다.

function1이 div 값 업데이트와 같은 간단한 javascript를 실행하고 있는 경우 function1이 완료된 후 function2가 실행됩니다.

function1이 AJAX 콜과 같은 비동기 콜을 발신하는 경우 "콜백" 메서드를 작성해야 합니다(대부분의 AJAX API에는 콜백 함수 파라미터가 있습니다).다음으로 콜백의 function 2를 호출합니다.예:

function1()
{
  new AjaxCall(ajaxOptions, MyCallback);
}

function MyCallback(result)
{
  function2(result);
}

방법 2, 3, 4 이후에 방법 1을 실행해야 하는 경우.다음 코드 스니펫은 JavaScript에서 Deferred 개체를 사용하여 이 문제를 해결할 수 있습니다.

function method1(){
  var dfd = new $.Deferred();
     setTimeout(function(){
     console.log("Inside Method - 1"); 
     method2(dfd);	 
    }, 5000);
  return dfd.promise();
}

function method2(dfd){
  setTimeout(function(){
   console.log("Inside Method - 2"); 
   method3(dfd);	
  }, 3000);
}

function method3(dfd){
  setTimeout(function(){
   console.log("Inside Method - 3"); 	
   dfd.resolve();
  }, 3000);
}

function method4(){   
   console.log("Inside Method - 4"); 	
}

var call = method1();

$.when(call).then(function(cb){
  method4();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

function1이 비동기 함수로 변환하는 경우 완료에 시간이 걸리고 콜백을 추가할 수 없기 때문에 비동기 함수로 변환하는 경우

function function1 (someVariable) {
    var date = Date.now ();
    while (Date.now () - date < 2000);      // function1 takes some time to complete
    console.log (someVariable);
}
function function2 (someVariable) {
    console.log (someVariable);
}
function onClick () {
    window.setTimeout (() => { function1 ("This is function1"); }, 0);
    window.setTimeout (() => { function2 ("This is function2"); }, 0);
    console.log ("Click handled");  // To show that the function will return before both functions are executed
}
onClick ();

출력은 다음과 같습니다.

Click handled

...그리고 2초 후:

This is function 1
This is function 2

이는 window.setTimeout()을 호출하면 비동기 호출이 생성하는 JS 런틴 태스크루프에 태스크가 추가되기 때문입니다.또, JS 런타임의 「run-to-completion」의 기본 원칙은, onClick()이 종료되기 전에 중단되는 일이 없기 때문입니다.

코드를 이해하기 어렵게 만드는 만큼 재미있다는 것을 알아두세요...

언급URL : https://stackoverflow.com/questions/5000415/call-a-function-after-previous-function-is-complete

반응형