Ajax와 같은 비동기 호출을 호출하는 동안 코드를 대기시키는 방법
이 질문에 이미 답변이 있습니다.
- 비동기 호출에서 응답을 어떻게 반환합니까? 36 답변
이런 걸 찾고 있어요
function someFunc() {
callAjaxfunc(); //may have multiple ajax calls in this function
someWait(); // some code which waits until async calls complete
console.log('Pass2');
}
function callAjaxfunc() {
//All ajax calls called here
console.log('Pass1');
}
내가 무엇을 시도 했습니까?
1 Jquery.when ()
그것을 사용해 보았습니다 .. 잘 작동합니다. 하지만 내가 원하는 방식은 아닙니다. $.when
기다릴 것이지만 옆의 코드는 기다리지 않고 $.when()
실행됩니다. 내부 코드 do callback
는 ajax 호출 후에 만 실행됩니다.
2. 전역 플래그가있는 setTimeOut ()
나는 이것이 효과가있을 것이라고 확신했다. 나는 다음과 같이 시도했다.
GlobalFlag = false;
function someFunc()
callAjaxfunc(); //may have multiple ajax calls in this function
setTimeOut(waitFunc, 100); // some which waits until async calls complete
console.log('Pass2');
}
function callAjaxfunc() {
//All ajax calls called here
onAjaxSuccess: function() {
GlobalFlag = true;
};
console.log('Pass1');
}
function waitFunc() {
if (!GlobalFlag) {
setTimeOut(waitFunc, 100);
}
}
여전히 원하는 결과를 얻을 수 없습니다. 내가 여기서 뭔가 잘못하고 있니? 이게 방법이 아니야?
내가 원했던 결과는 이렇게 나와야
Pass1
Pass2
AJAX 호출이 필요하므로 바이올린을 만들 수 없습니다.
EDIT: As many were suggesting callbacks..i know about them..but still the code next to somewait()
will get executed...I want browser to completely stop executing code next to somewait()
until the ajax call..Also it may be a bad practice but worth to know and try if possible...
Use callbacks. Something like this should work based on your sample code.
function someFunc() {
callAjaxfunc(function() {
console.log('Pass2');
});
}
function callAjaxfunc(callback) {
//All ajax calls called here
onAjaxSuccess: function() {
callback();
};
console.log('Pass1');
}
This will print Pass1
immediately (assuming ajax request takes atleast a few microseconds), then print Pass2
when the onAjaxSuccess
is executed.
Why didn't it work for you using Deferred Objects
? Unless I misunderstood something this may work for you.
/* AJAX success handler */
var echo = function() {
console.log('Pass1');
};
var pass = function() {
$.when(
/* AJAX requests */
$.post("/echo/json/", { delay: 1 }, echo),
$.post("/echo/json/", { delay: 2 }, echo),
$.post("/echo/json/", { delay: 3 }, echo)
).then(function() {
/* Run after all AJAX */
console.log('Pass2');
});
};
UPDATE
Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async
to false
in your $.ajax
requests to make them blocking. This will hang your browser until the request is finished though.
Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.
Real programmers do it with semaphores.
Have a variable set to 0
. Increment it before each AJAX call. Decrement it in each success handler, and test for 0
. If it is, you're done.
If you need wait until the ajax call is completed all do you need is make your call synchronously.
'program story' 카테고리의 다른 글
사진에서 종이 시트의 모서리를 감지하는 알고리즘 (0) | 2020.09.06 |
---|---|
웹 서버, 웹 컨테이너 및 응용 프로그램 서버의 차이점 (0) | 2020.09.06 |
Flash없이 클립 보드에 복사 (0) | 2020.09.06 |
열거 형 및 일치하는 속성에 대한 C # 명명 규칙 (0) | 2020.09.06 |
마우스 오버시 rgba 배경색의 알파 만 변경할 수 있습니까? (0) | 2020.09.06 |