<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function foo() {
// console.log('foo!!');
function bar() {
console.log('bar!!');
return '메롱';
}
return bar; // 함수 bar를 통째로 호출
// return bar(); // bar를 호출해서 return값 '메롱' 반환
}
const f = foo();
const result = f();
console.log('result: ', result);
</script>
</body>
</html>
함수안에 데이터를 꺼낼수 있다는 것을 알수 있다.

# Promise
# Promise: 비동기 통신을 할 때 상태에 따른
콜백함수들을 관리해주는 객체
1. 상태 (state)
- pending: 요청을 수행중
- fulfilled: 요청을 성공
- rejected: 요청을 실패
2. Promise객체는 2개의 콜백함수를 매개변수로 가집니다.
- a. resolve: 요청 성공시 처리하는 함수
- b. reject: 요청 실패시 처리하는 함수
/*
-Promise 내부 데이터 소비
1. then(): Promise가 fulfilled(성공) 상태일 때 데이터후속처리 수행
2. catch(): Promise가 rejected(실패) 상태일 때 데이터후속처리 수행
*/
// Promise로 callback 지옥 해결예시
/*
#3번 게시물 상세조회해서
-> 작성자의 계정명을 알아낸 후 해당 사용자의 정보를 가져온다.
-> 해당 사용자의 정보를 이용해서 친구목록을 불러온다.
-> 그리고 선택된 친구들에게 단체쪽지를 보낸다.
*/
<script>
function get(url) {
return new Promise((resolve, reject) => {
//요청 처리
const xhr = new XMLHttpRequest;
xhr.open('GET', url);
xhr.send();
xhr.onload = e => {
if (xhr.status === 200) {
//요청 성공시에는 resolve콜백을 호출
resolve(JSON.parse(xhr.response)); // 리턴하고 싶은 값을 괄호에 넣어준다.
} else {
//실패시에는 reject를 호출
reject('통신 실패!');
}
};
});
}
(function () {
const result = get('http://localhost:5000/board');
console.log(result);
result.then((boardList) => {
console.log('결과:',boardList);
});
// Promise로 callback 지옥 해결예시
get('/board/3').then(articleInfo => { return get('/user/+articleInfo.userAccount');})
get('/board/3').then(articleInfo => get('/user/+articleInfo.userAccount')) // 리턴 중괄호 생략 가능
// 예시
get('/board/3').then(articleInfo => get('/user/+articleInfo.userAccount'))
.then(userInfo => get('/friends'))
.then(friendList => {
});
})();
</script>
'Spring' 카테고리의 다른 글
[Spring / 댓글 비동기요청 #1] _ 22.07.29 [13일차] (0) | 2022.07.29 |
---|---|
[Spring / 비동기 # 12] fetch(GET)_실무!_22.07.29 [13일차] (0) | 2022.07.29 |
[Spring / 비동기 #10] ajax의 문제 해결(콜백지옥)_22.07.29 [13일차] (0) | 2022.07.29 |
[Spring / 비동기 #9] ajax의 문제점_22.07.29 [13일차] (0) | 2022.07.29 |
[Spring / 비동기 #8] RESTful_scoreApp 실습_22.07.29 [13일차] (0) | 2022.07.29 |