[JS & ES6 신문법 학습] ES6 Promise 간단 연습문제 & 해설

김범기·2024년 7월 17일

JAVASCRIPT

목록 보기
30/38
post-thumbnail

문제1

Q1. 이미지 로딩 성공시 특정 코드를 실행하고 싶습니다.

HTML 안에 있는 이미지 로딩이 끝나면 무언가 코드를 실행하고 싶습니다.

<img id="test" src="https://codingapple1.github.io/kona.jpg"> 

이 이미지가 로드가 되면 콘솔창에 성공, 로드가 실패하면 콘솔창에 실패를 출력하고 싶은데

Promise 문법의 then, catch 함수를 사용해 만들고 싶습니다. 어떻게 코드를 짜면 될까요?

(참고) 이미지 로딩이 끝났다는 것은 에 load라는 이벤트리스너를 붙여서 체크가 가능합니다.

(참고) 이미지 로딩이 실패했다는 것은 에 error라는 이벤트리스너를 붙여서 체크가 가능합니다.

난 아래 처럼 했다.

var 프로미스 = new Promise(function(resolve, reject){
  const testImg = document.querySelector('#test')
  testImg.addEventListener('load', function(){
    resolve()
  })
  testImg.addEventListener('error', function(){
    reject()
  })
})

프로미스.then(function(){
  console.log('됨')
}).catch(function(){
  console.log('안됨')
})

정답은 아래와 같다.

var 이미지로딩 = new Promise(function(성공, 실패){
  var img = document.querySelector('#test');
  img.addEventListener('load', function(){
      성공();
  });
  img.addEventListener('error', function(){
      실패();
  });
  
});


이미지로딩.then(function(){
  console.log('성공했어요')
}).catch(function(){
  console.log('실패했어요')
})

이렇게 짤 수 있겠습니다.

프로미스 안에서는 성공(), 실패()가 실행되는 경우의 수를 만들어주시면 되고

그렇게 하면 이제 .then() .catch()를 이용해서 성공/실패시 특정 코드들을 실행할 수 있습니다.

끝입니다.


문제2

Q2. Ajax 요청이 성공하면 무언가 코드를 실행하고 싶습니다.

https://codingapple1.github.io/hello.txt 라는 경로로 GET 요청을 하면 인삿말이 하나 딸려옵니다.

여기로 GET 요청을 해서 성공하면

Promise의 then 함수를 이용해서 Ajax로 받아온 인삿말을 콘솔창에 출력해주고 싶습니다.

어떻게 하면 될까요?

(jQuery done함수 자체에 Promise 기능이 있기 때문에 코드가 약간 중복도 많고 쓸데없을 수 있지만 연습삼아 해봅시다.)

이것은 jQuery Ajax 편리하니까 jQuery CDN 파일

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> ```
Ajax 어떻게 하는지 힌트좀
 

일단 jQuery로 Ajax 요청을 하려면 $.ajax혹은 $.get을 쓰시면 됩니다.

(그리고 jQuery 설치 파일이 상단에 첨부되어있어야겠죠?)

 

$.ajax({
  type : 'GET',
  url : 'URL 경로'
})


$.get('URL 경로')
둘중 하나 마음에 드는거 쓰시면 URL 경로 상에 있는 데이터를 가져올 수 있습니다. 

그리고 가져온 데이터를 출력하거나 가져온 후에 특정 코드를 실행하고 싶다면 

$.ajax({
  type : 'GET',
  url : 'URL 경로'
}).done(function(결과){
  console.log(결과);
});


$.get('URL 경로').done(function(결과){
  console.log(결과)
});
done함수를 뒤에 붙여서 이렇게 쓰시면 됩니다.

결과라는 파라미터에 여러분이 가져온 데이터가 담겨져있습니다. 

왜 내 컴퓨터에서는 안되는지 현재로서는 모르겠지만 일단 아래와 같이 풀었고. 정답도 똑같았다.

<script src="https://code.jquery.com/jquery-3.4.1.min.js">
  var 프로미스 = new Promise(function(성공, 실패) {
    $.get('https://codingapple1.github.io/hello.txt').done(function(결과){
      성공(결과)
    });
  });

프로미스.then(function(결과) {
  console.log(결과);
})
</script>

jquery 작동 안되는 것 해결

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
    <div>
        <h1>gd</h1>
    </div>
    
    <!-- <script src="https://code.jquery.com/jquery-3.4.1.min.js"> -->
    <script>

      var 프로미스 = new Promise(function(성공, 실패) {
          $.get('https://codingapple1.github.io/hello.txt').done(function(결과){
            성공(결과)
          });
      });

      프로미스.then(function(결과) {
        console.log(결과);
      })
      
    </script>
</body>
</html>

이런식으로 jquery를 script코드를 head에 작성한 후 나머지 jquery코드를 body의 script에 작성하니 해결되었다.


문제3

Q3. Promise chaining

2번 문제에서 https://codingapple1.github.io/hello.txt 라는 경로로 GET 요청을 한 뒤에

.then을 이용해 인삿말을 콘솔창에 출력해보았습니다.

이번엔 그 직후 https://codingapple1.github.io/hello2.txt 라는 경로로 GET 요청을 또 하고

.then을 이용해 인삿말을 또 출력해보고 싶습니다.

쉽게 말하면

  1. hello.txt GET 요청

  2. 그게 완료되면 hello2.txt GET 요청

  3. 그게 완료되면 hello2.txt 결과를 콘솔창에 출력

을 하고 싶다는 말입니다.

2번에서 만든 코드를 어떻게 업데이트하면 될까요?

힌트1) 프로미스.then(()=>{둘째실행할거}).then(()=>{셋째실행할거})

이렇게 then을 여러개 이어붙여 만들어봅시다.

힌트2) .then()은 당연히 new Promise()로 생성한 프로미스 오브젝트들에 붙일 수 있습니다.


아래처럼 해결하면 된다.
.then을 또 작성해주고, 첫 번째 then()

console.log(결과)

이후에 retunr new Promise()를 이용해서 뒤에 then을 사용할 수 있게 한다.

var 프로미스 = new Promise(function(성공, 실패) {
  $.get('https://codingapple1.github.io/hello.txt').done(function(결과){
    성공(결과)
  });
});

프로미스.then(function(결과) {
  console.log(결과);
  return new Promise(function(성공, 실패){
    $.get('https://codingapple1.github.io/hello2.txt').done(function(결과){
      성공(결과)
    });
  })
}).then(function(결과){
  console.log(결과)
})

그리고 코드가 유사하니까 함수를 만들어서 사용해보자.

아래처럼 하면 된다.

var 프로미스 = URL요청('https://codingapple1.github.io/hello.txt')

프로미스.then(function(결과) {
  console.log(결과);
  return URL요청('https://codingapple1.github.io/hello2.txt')
}).then(function(결과){
  console.log(결과)
})

function URL요청(해당URL){
  return new Promise(function(성공, 실패){
    $.get(해당URL).done(function(결과){
      성공(결과)
    });
  })
}
profile
반드시 결승점을 통과하는 개발자

0개의 댓글