프라미스 체이닝(promise chaining)
result 가 .then 핸들러의 체인을 통해 전달된다는 점에서 착안한 아이디어
예시
- fetch 이용
fetch('/article/promise-chaining/user.json')
// 원격 서버가 응답하면 .then 아래 코드가 실행됩니다.
.then(function(response) {
// response.text()는 응답 텍스트 전체가 다운로드되면
// 응답 텍스트를 새로운 이행 프라미스를 만들고, 이를 반환합니다.
return response.text();
})
.then(function(text) {
// 원격에서 받아온 파일의 내용
alert(text); // {"name": "Violet-Bora-Lee", "isAdmin": true}
});
-- 간단하게 변경
fetch('/article/promise-chaining/user.json')
.then(response => response.json())
.then(user => alert(user.name));
- fetch + 함수
fetch('/article/promise-chaining/user.json')
.then(response => response.json())
.then(user => fetch(`https://api.github.com/users/${user.name}`))
.then(response => response.json())
.then(githubUser => new Promise(function(resolve, reject) { // (*)
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
setTimeout(() => {
img.remove();
resolve(githubUser); // (**)
}, 3000);
}))
// 3초 후 동작함
.then(githubUser => alert(`${githubUser.name}의 이미지를 성공적으로 출력하였습니다.`))
-- 간략화 ( 함수단위로 분해)
function loadJson(url) {
return fetch(url)
.then(response => response.json());
}
function loadGithubUser(name) {
return fetch(`https://api.github.com/users/${name}`)
.then(response => response.json());
}
function showAvatar(githubUser) {
return new Promise(function(resolve, reject) {
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
setTimeout(() => {
img.remove();
resolve(githubUser);
}, 3000);
});
}
// 함수를 이용하여 다시 동일 작업 수행
loadJson('/article/promise-chaining/user.json')
.then(user => loadGithubUser(user.name))
.then(showAvatar)
.then(githubUser => alert(`Finished showing ${githubUser.name}`));
// ...
참고자료
'프로그래밍 > JavaScript' 카테고리의 다른 글
[ JS ] 프라미스와 async / await : 프라미스 API (0) | 2024.06.05 |
---|---|
[ JS ] 프라미스와 async / await : 프라미스와 에러 핸들링 (0) | 2024.06.05 |
[ JS ] 프라미스와 async / await : promise (0) | 2024.06.04 |
[ JS ] 프라미스와 async / await : 콜백 (0) | 2024.06.03 |
[ JS ] 원시값, 참조값, 얕은 복사, 깊은 복사 (0) | 2024.05.20 |