데이터 값을 확인하려고 함수안에 ajax문을 넣어서 서버에서 true/false값을 받아옵니다.
예를 들어
function test() {
var data = {};
data = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
var result = JSON.parse(xhr.responseText);
if (result.result !== true) return;
///데이터에 true/false 담겨져옴
}
};
xhr.open("POST", "/test");
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(data);
}
이런 방식으로 불러옵니다. 사용목은
if(test() === true) {
코드...
}
이런 방식으로 사용하고 싶은데
ajax로 받아온 데이터자리에서 test함수로 리턴시키는 방법이 있을까요?
이 문서를 참고하시면 좋을 듯합니다. 비동기를 지원하는 환경이라면 아래의 코드로 대체하는 게 가능합니다.
function test() {
return new Promise((res, rej) => {
var data = {};
data = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
var result = JSON.parse(xhr.responseText);
res(result.result); // 성공적으로 완료됐을 경우 res에 값을 넘겨서 함수 밖에서 사용 가능 예외 처리는 rej에서
}
};
xhr.open("POST", "/test");
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(data);
});
}
이렇게 하면 test() 함수는 Promise<boolean>을 리턴하는 함수가 되고, if (await test()) { ... }로 사용이 가능합니다. await를 쓰게 되면 해당 코드가 처리될 때까지 스레드가 정지하므로, test()를 동시에 여러 번 사용해야 한다면 .then(res => { ... })을 이용하시면 됩니다.
test().then(res => {
if (res) { // res의 값이 boolean임
// 대충 굉장하고 엄청난 코드
}
}).catch(e => {
// test()에서 Promise의 rej로 넘긴 값이 넘어옴.
});