이전 기능이 완료된 후 기능 호출
다음 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를 사용하는 경우 새로운 Deferreds 패턴을 사용할 수 있습니다.
$('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();
}
})
이 답변은 표준 promises
의 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
});
}
This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then
statements:
function1(someVariable).then(function() {
function2(someOtherVariable);
}).then(function() {
function3();
});
You can also wrap jQuery deferrds easily (which are returned from $.ajax
calls):
Promise.resolve($.ajax(...params...)).then(function(result) {
//whatever you want to do after the request
});
As @charlietfl noted, the jqXHR
object returned by $.ajax()
implements the Promise
interface. So it is not actually necessary to wrap it in a Promise
, it can be used directly:
$.ajax(...params...).then(function(result) {
//whatever you want to do after the request
});
Or you can trigger a custom event when one function completes, then bind it to the document:
function a() {
// first function code here
$(document).trigger('function_a_complete');
}
function b() {
// second function code here
}
$(document).bind('function_a_complete', b);
Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.
This depends on what function1 is doing.
If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.
If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:
function1()
{
new AjaxCall(ajaxOptions, MyCallback);
}
function MyCallback(result)
{
function2(result);
}
you can do it like this
$.when(funtion1()).then(function(){
funtion2();
})
I had a problem with this. Despite using the above code, it wasn't working. Later with others help I realized that my first function was asynchronous and second function was synchronous.
Hence the asynchronous one was getting executed after the synchronous function despite the code I wrote.
I found a workaround in my case by calling the second function at the end of my first function.
If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :
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 ();
The output will be :
Click handled
...and after 2 seconds :
This is function 1
This is function 2
This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.
Notice that this as funny as it may the code difficult to understand...
참고URL : https://stackoverflow.com/questions/5000415/call-a-function-after-previous-function-is-complete
'IT' 카테고리의 다른 글
Objective-C가 NSString을 전환 할 수 있습니까? (0) | 2020.05.31 |
---|---|
ASP.NET CORE에서 클라이언트 IP 주소를 어떻게 얻습니까? (0) | 2020.05.31 |
연관 배열 객체의 Javascript foreach 루프 (0) | 2020.05.31 |
JavaScript에는 stringbuilder 클래스가 내장되어 있습니까? (0) | 2020.05.31 |
문자열에서 모든 공백을 제거하는 방법 (0) | 2020.05.31 |