2021 프론트 엔드 로드맵 따라가기/JS
AJAX 이용 시 주의할 점
알 수 없는 사용자
2021. 6. 7. 22:20
1. onload 콜백함수 내부에서 this 사용
...
// onload에 할당된 함수가 callback 함수로 이용되기 때문에 실제 동작시 this가 가리키는 객체가 달라짐에 주의하자.
let self = this;
this.http.onload = function () {
// if (this.http.status === 200) <=== error
if (self.http.status === 200) {
return self.http.responseText;
}
};
...
2. 비동기 요청의 결과를 리턴 받을 때
const easyHttp = new EasyHttp();
const posts = easyHttp.getRequest("https://jsonplaceholder.typicode.com/posts", null);
console.log(posts); // undefined, 즉 위의 작업이 끝나지 않고 해당 라인이 실행됨
따라서 아래와 같이 콜백함수를 이용한다.
const easyHttp = new EasyHttp();
easyHttp.getRequest("https://jsonplaceholder.typicode.com/posts", getPosts);
function getPosts(posts) {
console.log(posts);
}
3. 콜백함수 작성 시 error를 대비하자
const easyHttp = new EasyHttp();
easyHttp.getRequest("https://jsonplaceholder.typicode.com/posts", getPosts);
// error 인자를 만들어서 error handling이 가능하도록 작성
function getPosts(error, posts) {
if (error) {
console.log(error);
} else {
console.log(posts);
}
}