텍스트파일 읽기

function readTxt(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open(“GET”, file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status === 0)
{
allText = rawFile.responseText.split(’\n’);
alert(allText[4]);
}
}
};
rawFile.send(null);
}

readTxt(“file:////rules.txt”);

alert(allText);

함수안에서는 allText가 잘 채워지고 잘 출력되는데 함수밖으로 나오면 undefined가 출력됩니다. 그리고 alert 뜨는것도 함수밖이 먼저 실행되고 다음으로 readTxt함수안에 있는 alert이 다음으로 뜨는데 해결방법 아시는 분 계실까요?

비동기로 리퀘스트가 작동하기 때문입니다. Statechange 에서 부터 텍스트를 사용할 수 있고 이후 작업은 콜백이나 함수내부에서 진행하여야 합니다. 아니면 async/await을 쓰는 것도 좋은 방법입니다