JavaScript ES6 문법 - Promise

Apeachicetea·2021년 11월 4일
0

JavaScript ES6

목록 보기
5/6

Promise

성공 / 실패 판정 기계
성공 / 실패의 경우에 맞춰 각각 다른 코드 실행 가능

기본 사용법


  let 프로미스 = new Promise(function(resolve, reject){
    let sum = 1 + 1;
    resolve(sum);
    //성공 판정
    //파라미터로 sum의 결과값을 성공일 경우 실행할 코드에 전달할 수 있다.
    reject();
    //실패 판정
  })

  프로미스.then(function(a) {
  //프로미스가 성공일 경우 실행할 코드
    console.log(a); // 2; 
  }).catch(function() {
  //프로미스가 실패일 경우 실행할 코드
    console.log('실패했쪄염ㅠㅠ');  
  })

예시

img태그가 로드가 성공하면 콘솔창에 '성공', 실패하면 '실패'가 뜨게 된다.

//html

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

  let promise = new Promise(function(resolve, reject){
    const img = document.querySelector('#test');

    img.addEventListener('load', function(){
      resolve();
    })

    img.addEventListener('error', function(){
      reject();
    })

  });

  promise.then(function(){
    console.log('성공');
  }).catch(function(){
    console.log('실패');
  });

콘솔

  1. 기본 사용법에서 성공시 실행된 코드에 sum의 결과값이 전달된 것을 확인 할 수 있다.
  2. 이미지가 로드에 성공해서 콘솔창에 '성공'이 출력되는 것을 볼 수 있다.

profile
웹 프론트엔드 개발자

1개의 댓글

comment-user-thumbnail
2025년 9월 18일

My friends recommended that I try https://www.tenderbang.com/gay-hookup.html, a casual hookup site, so I decided to give it a go. The profiles were engaging and the messaging was straightforward, full of playful banter that quickly became more intimate. I ended up connecting with someone local, and our chats quickly became flirty and hot without any awkwardness. It was refreshing to find a space where people were honest about what they wanted. This made the whole experience feel smooth, spontaneous and surprisingly satisfying.

답글 달기