나는 다음 JavaScript 코드:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});
Function1 function2 '만' '어떻게' 완료된 후 호출됨 있는지?
익명의 대체하십시오 콜백하는, 저회가 function1 동의하십시오 있다.
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
...do stuff
callback();
}
$('a.button').click(function(){
if(condition == 'true'){
$.when(function1()).then(function2());
}
else {
doThis(someVariable);
}
});
레베카 머어어프! 그동안 훌륭한 요약 여기있을 있습니다. http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/
새로운 길을 비동기적입니다 작업을 처리할 수 있다 (및 훨씬 뛰어난) 공약을 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
});
}
올해 5월 이 간단한 것처럼 보이는 것은 상당한 오버헤드에 보여주고 있지만 좀 더 복잡한 코드를 사용하여 보다 훨씬 나은 콜백. 체인을 사용하여 여러 '다음' 명령문입니다 여러 비동기적입니다 페이징됩니다 쉽게 할 수 있습니다.
function1(someVariable).then(function() {
function2(someOtherVariable);
}).then(function() {
function3();
});
Jquery 디퍼즈 쉽게 줄 수도 있습니다 ("에서 $ 지아이아스 나님이시거늘 있는 '페이징됩니다):
Promise.resolve($.ajax(...params...)).then(function(result) {
//whatever you want to do after the request
});
이 ',' 에서 '$ 로 언급된 @charlietfl 이크스어 객체에는 지아이아스 ()' 는 '약속' 반환되었습니다 인터페이스입니다. 그래서 필요한 것이 아니라 '약속' 이 실제로 마무리를 지을 경우 it 직접 사용할 수 있습니다.
$.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);
B& # 39, & # 39 이 방법을 사용하여 함수. 이후, a& # 39, & # 39 실행하십시오 기능을 할 수 있을 것 같이 있을 때 a 는 촉발제였군 전용 함수 실행 하였다.
이 내용에 따라 다릅니다 function1 하고 있다.
몇 가지 간단한 이은크루누스 등의 조치를 취할 경우 function1 function2 불지옥의 function1 후 뭔가 관심용 값이거나 업데이트하더라도 javascript div 가 완료되었습니다.
이 경우, AJAX 호출, 비동기 호출 function1 만드는 등, callback" " 작성해야 합니다. 방법 (대부분의 아약스 API& # 39 의 투명지에 콜백 함수에 매개 변수). 이 후 function2 호출하십시오 콜백하는. 예:
function1()
{
new AjaxCall(ajaxOptions, MyCallback);
}
function MyCallback(result)
{
function2(result);
}
방법 1 은 메서드로부터 후 실행할 경우 2, 3, 4. 이를 위해 다음 코드를 사용하여 JavaScript 에서 우회된 객체에는 스니핏 해결책이 될 수 있습니다.
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
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 경우 비동기식 보기할 선반가공 agent. 한 시간이 다소 걸릴 수 있으며, 이를 콜백하는 추가하기에서는 완료하십시오 제어할 수 없습니다.
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
.and 이후 2 초.
This is function 1
This is function 2
이 때문에 작동됨 빈다우스세티메우스 호출하십시오 추가하기에서는 임무를 JS 런타인 루프 () 는 어떤 작업을 할 수 있는 데다 비동기식 호출하십시오 기본 원칙은 " run-to-completion"; js 런타임용으로 개발하십시오 온 클릭 () 는 절대 중단될 수 있어 이 전에 끝난다.
이 같은 코드를 이해하기 어려운 이상한 것을 알 수 있습니다.