2017-10-01 2 views
-2

페이지를로드 할 때 호출해야하는 함수가 2 개 있습니다. 다른 요청을 보내기 전에 기다려주십시오. [자바 스크립트]

window.addEventListener("load", function(e) { 
    func_a(); //send request to server (Node js) 
    func_b(); //send request to server (Node js) 
}); 

func_a

서버에 바로 목록을 업데이트하고 .end에 의해 반환하지 않습니다 요청을 보낼 것입니다. func_b()의 요청이 실제로 아무것도 있습니다 .. 다른 요청하기 전에 전송되지 및 통지 어떤 이유로
func_b() should send a request to the server and notify to all responses in the list. 

하지만.

왜 그런가?

편집 :

function func_a() { 

    var xhttp = new XMLHttpRequest(); 

    xhttp.addEventListener('load', function (e) { 
    if(xhttp.status != 200){ 
     //handle error 
     return; 
    } 
    handle_func(this.responseText); 
    func_a(); 
    }); 

    xhttp.open("GET", "ajax_info.txt", true); 
    xhttp.send(); 

} 
+1

좋은 아이디어는 체인 약속하는 것입니다 약속을 반환하면 ES7에 익숙하다면 async-await의 땅이다. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 그러면 then() 메소드를 사용하여 요청을 차례로 보낼 수 있습니다. –

답변

0

아약스는 비동기 적으로 작동하므로 두 번째 전에 첫 번째 요청을 완료 보장 할 수 없습니다. 당신이 원하는 경우에 따라서는 Promise를 사용하여 첫 번째 요청

function func_a(callback) { 

    var xhttp = new XMLHttpRequest(); 

    xhttp.onreadystatechange = function() { 

    if (this.readyState == 4 && this.status == 200) { 
     callback(); 
    } 

    }; 

    xhttp.open("GET", "ajax_info.txt", true); 
    xhttp.send(); 

} 

function func_b() { 

    var xhttp = new XMLHttpRequest(); 

    xhttp.onreadystatechange = function() { 

    if (this.readyState == 4 && this.status == 200) { 
     // Do something here 
    } 

    }; 

    xhttp.open("GET", "ajax_info2.txt", true); 
    xhttp.send(); 

} 

func_a(func_b); 
+0

먼저 감사합니다. 너의 답. 나는 그것에 대해서도 생각했지만 제 func_a (편집 중)를 보시고 func_b를 한 번만 불러오고 싶습니다 (페이지로드 중) –

+0

@zak_p func_a를 여러 번 호출해야합니까? – faressoft

0

에 대한 콜백 함수로 제공하여 첫 번째가 완료된 후 두 번째 요청을해야하는 것은 공평 뭔가 같은 :

func_a().then(() => { 
    console.log('Hi I am callback of func_a'); 
    func_b().then(() => { 
    console.log('Hi i am callback of func_b') 
    }) 
}) 

function func_a() { 
    return new Promise((resolve, reject) => { 
    var xhttp = new XMLHttpRequest(); 

    xhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
     resolve(); 
     } else { 
     reject() 
     } 
    }; 

    xhttp.open('GET', 'ajax_info.txt', true); 
    xhttp.send(); 
    }); 
} 

function func_b() { 
    return new Promise((resolve, reject) => { 
    var xhttp = new XMLHttpRequest(); 

    xhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
     resolve(); 
     } else { 
     reject() 
     } 
    }; 

    xhttp.open('GET', 'ajax_info2.txt', true); 
    xhttp.send(); 
    }); 
} 

주 : 준비 기능이 패러다임을 사랑 그래서 & 경우, 귀하의 기능은 약속을 반환하는 정류한다 실행이 비동기 참조로 HTTP 요청을

async function myCalls() { 
    await func_a(); 
    func_b(); 
} 

myCalls(); 
관련 문제