본문 바로가기
JS

ES6 Promise 연습문제

by 케찹이 2024. 2. 25.

 

브금온!

 

 

 

Q1. <img> 태그의 이미지 로딩 성공시 특정 코드를 실행하고 싶다!

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

 

답:

더보기
<img id="test" src="https://codingapple1.github.io/kona.jpg" />
<script>
  const image = document.querySelector("img");
  let promise = new Promise(function (resolve, reject) {
    image.addEventListener("load", () => {
      resolve();
    });
    image.addEventListener("error", () => {
      reject();
    });
  });

  promise
    .then(function () {
      console.log("성공!");
    })
    .catch(function () {
      console.log("실패!");
    });
</script>

 

 

resolve는 조건을 만족했을 때 사용되는 함수, reject는 반대이다. resolve를 부르면 .then()을 쓰고, reject이면 catch()를 사용한다.

 

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

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

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

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

어떻게 하면 될까요?

 

답:

더보기
  let promise2 = new Promise(function (resolve, reject) {
    $.ajax({
      type: "GET",
      url: "https://codingapple1.github.io/hello.txt",
    }).done(function (결과) {
      resolve(결과);
    });
  });
  
    promise2
    .then(function (결과) {
      console.log(결과);
    });

Q3. Q2문제에 이어서 다른 경로에서 GET요청을 받고 해당 메시지를 이어서 출력하는 코드를 만들어보자. 

 

답:

더보기
  let promise2 = new Promise(function (resolve, reject) {
    $.ajax({
      type: "GET",
      url: "https://codingapple1.github.io/hello.txt",
    }).done(function (결과) {
      resolve(결과);
    });
  });

  promise2
    .then(function (결과) {
      console.log(결과);
      return new Promise(function (resolve, reject) {
        $.ajax({
          type: "GET",
          url: "https://codingapple1.github.io/hello2.txt",
        }).done(function (결과) {
          resolve(결과);
        });
      });
    })
    .then(function (결과) {
      console.log(결과);
    });

전반적으로 Promise의 사용방법 그리고 사용하는 이유를 알 수 있었던 문제들이었다.

마지막 문제를 풀며 느낀점은 promise를 사용하니 코드가 많이 복잡해보인다, promise를 개선하기 위해서 async/await을 사용하는 것 같다. 해당 개념을 공부해보자.

'JS' 카테고리의 다른 글

flex 개념, 특징 정리  (0) 2024.02.27
[HTML/CSS/JS] to do list 만들어보기 회고  (0) 2024.02.27
constructor, prototype 연습문제  (0) 2024.02.24
Spread, rest 파라미터 연습문제  (0) 2024.02.24
변수 퀴즈  (0) 2024.02.23

댓글