자바스크립트는 싱글 쓰레드이다. 그래서 비동기를 동기식으로 처리하는 것이 필수적이다
이를 위해 콜백함수를 사용해왔는데
콜백함수의 단점인 콜백지옥으로 인해 코드의 가독성이 떨어지고 유지보수도
힘들어 이를 해결하기 위해 ES6에서는 Promise가 표준 내장 객체로 추가되었다.
Promise는 비동기 작업을 동기 작업으로 처리하기 위한 객체이다.
비동기 작업에 대하여, 비동기 작업이 완료된 후 결과 값 또는 실패의 이유를 콜백 함수(resolve,reject)로 전달
- Promise는 3가지 상태값을 가지고 있다(ajax랑 비슷하군)
Pending(대기) : 비동기 처리 로직이 아직 완료되지 않은 상태
Fullfilled(이행) : 비동기 처리가 완료되어 Promise가 결과값을 반환해준 상태(resolve()실행)
Rejected(실패) : 비동기 처리가 실패하거나 오류가 발생한 상태(reject()실행)
promise 객체
예제2
즉 promise객체가 이행상태(resolve()호출로 테스트 )면 then(콜백함수)의 인자인 콜백함수가 자동으로 실행되고
새로운 Promise객체를 반환한다.
promise객체가 실패상태(reject()호출로 테스트 )면 catch(콜백함수)의 인자인 콜백함수가 자동으로 실행되고
새로운 Promise객체를 반환한다.
비동기작업의 결과 데이터 성공시는 resolve(결과데이터) 호출 시 then (콜백함수 (결과데이터를 받을 변수))
실패시는 reject(결과데이터) 호출 시 catch (콜백함수 (결과데이터를 받을 변수))
예제3
에제4
new Promise(function(resolve, reject){
//비동기 코드 사용
/*
$.get('https://jsonplaceholder.typicode.com/posts/1',
function (response) {
if (response) {
resolve(response);
}
reject(new Error("Request is failed"));
}
); */
//ajax 사용
$.ajax({url:'https://jsonplaceholder.typicode.com/posts/1'}).
done(function(response){
resolve(response)
}).fail(function(e){
reject(e)
});
}).then(function (data) {
console.log(data); //성공
}).catch(function (e) {
console.log(e); //실패
});
예제5
함수 정의 후 맨 밑 두줄 실행
const res = getPosts();
console.log('비동기 함수인 getPosts()호출(res):',res);
getPosts() 호출 후 바로 밑에 코드가 실행 됨! 요거 실행이 완료되기 전에 밑에 코드가 이미 호출되기 때문에
const res = getPosts()는 undifined 가 나옴...
그래서? 비동기를 동기로 만들어야 이 코드가 끝나야 밑에 코드가 순차적으로 실행되어서
undifined가 안나옴 !!!! 그래서 getPosts를 promise함수로 변경해야 한다는 것!!!
function getPosts(){
//XMLHttpRequest 객체 생성
const xhr = new XMLHttpRequest();
//HTTP 메소드 및 요청 URL설정
xhr.open('GET','https://jsonplaceholder.typicode.com/posts');
//서버에 전송
//JSON으로 보낼 때는 반드시 문자열로 변환
xhr.send( );
xhr.onload = ( ) =>{ // 서버로부터 응답을 받았을 때 발생하는 이벤트 : load이벤트
console.log(xhr);
console.log('응답 상태 코드:',xhr.status);
if(xhr.status == 200){
const res=JSON.parse(xhr.response);//JSON객체로 변환
console.log('응답데이타:',res);
return res;
}
else{
console.log('응답 에러:',xhr.statusText);
return;
}
};
}
//const res = getPosts();
*****//console.log('비동기 함수인 getPosts()호출(res):',res);//undefined*******
아무리 위에코드가 빨라도 undefined
그래서!!
function getPostsPromise(){
return new Promise((resolve,reject)=>{
const xhr = new XMLHttpRequest();
xhr.open('GET','https://jsonplaceholder.typicode.com/posts');
xhr.send();
xhr.onload = () =>{
console.log(xhr);
console.log('응답 상태 코드:',xhr.status);
if(xhr.status ==200){
const res=JSON.parse(xhr.response);//JSON객체로 변환
console.log('응답데이타:',res);
resolve(res);
}
else{
console.log('응답 에러:',xhr.statusText);
reject(new Error('에러'));
}
};
});
}
getPostsPromise()
.then(res=>console.log(res))
.catch(e=>console.log(e));
아 이거 다 못침.... 제길
-프로미스의 에러 처리
then(success콜백).catch( 잡기 !! )
'학원 > REACT' 카테고리의 다른 글
02/17 [React] 진짜 React 환경설정 및 문법정리 (1) | 2023.02.17 |
---|---|
02/17 [React] async/await (0) | 2023.02.17 |
02/16 [React] 객체복사 (0) | 2023.02.16 |
02/16 [React] Spread연산자,구조분해 (1) | 2023.02.16 |
0215 [REACT] import와 export (0) | 2023.02.15 |