반응형

 


Promise

 

Promise

자바스크립트에서 비동기 함수를 다루는 방법

 

Promise 생성문법

var myPromise1 = new Promise(function(resolve, reject) {
  resolve(1);
});

myPromise1.then();  //이행

 

Promise의 resolve(이행)와 reject(거부)

Promise라는 object를 갖고 then이란 콜백 함수를 요청하면 사용자 데이터를 등록한 대로 콜백 함수를 불러줄 수 있다.

var myPromise2 = new Promise(function(resolve, reject) {
  reject(1);		
});

myPromise2.then();	// 거부

 

 

예제1

getData()함수에 new Promise()를 호출할 때 콜백 함수의 인자를 resolve, reject로 선언.

이때, resolve를 실행해서 아래 선언된 메시지를 resolve 인자값으로 넘기기.

// new Promise()를 호출할 때 콜백 함수의 인자를 resolve, reject로 선언.
function getData() {
  return new Promise(function (resolve, reject) {
    //resolve를 실행해서 아래 선언된 메시지(data)를 resolve 인자 값으로 넘김.
    var data = 'javascript promise';
    resolve(data);
  });
}

// then을 이용해서 resolve()의 결과 값 data를 resolvedData로 받기.
getData().then(function (resolvedData) {
  document.write(resolvedData);
});

 

 

예제2

 

getPosts() 함수 작성 

posts 의 내용을 불러와 index.html에 표시하는 코드

//posts 변수
const posts = [
  { title: 'Post 1', body: '첫번째 게시글입니다.' },
  { title: 'Post 2', body: '두번째 게시글입니다.' },
  { title: 'Post 3', body: '세번째 게시글입니다.' },
  { title: 'Post 4', body: '네번째 게시글입니다.' },
  { title: 'Post 5', body: '다섯번째 게시글입니다.' },
];

function getPosts() {
  //setTimeout()를 사용해서 1초 후에 posts element를 rendering 합니다.
  setTimeout(() => {
    let output = '';
    //위에 정의된 posts 내의 게시글 제목과 내용을 forEach()을 사용해서 rendering 합니다.
    posts.forEach(post => {
      output = output + `<li>${post.title}<br> 내용: ${post.body} </li>`;
    });
    //rendering 된 게시글을 document.body.innerHTML을 사용해서 html에 띄어줍니다.
    document.body.innerHTML = output;
  }, 1000);
}

 

createPost() 함수 작성

이행 상태가 되면 then()을 이용하여 처리 결과 값을 받을 수 있다.

실패 상태가 되면 실패한 이유(실패 처리의 결과 값)를 catch()로 받을 수 있다.

function createPost(post) {
  //Promise를 생성해서 resolve와 reject를 인자로 받습니다.
  return new Promise(function (resolve, reject) {
    //Promise 내에 setTimeout으로 비동기 처리하는데,
    setTimeout(() => {
      // createPost()함수에 인자로 받아온 post를 push할 때
      posts.push(post);
      const error = false;
      // 에러없이 성공적으로 호출되면(if(!error)) `resolve`를 실행
      if (!error) resolve();
      // 그렇지 않으면 에러를 받아들이는 `reject`를 2초 후에 실행
      else reject('error: wrong');
    }, 2000);
  });
}

createPost({ title: 'Post N', body: 'N번째 게시글입니다.' })
  .then(getPosts)
  .catch(err => console.log(err));

 

 

 


fetch 이용해 json데이터 가져오기

 

 

비동기 함수인 fetch를 이용하면, json 파일을 읽을 수 있다.

function showHexaCode(e) { 
  // 새로고침 방지
  e.preventDefault()
  
  const userInputColor = inputElem.value 
  
  // fetch -> response.json() 하는 과정은 고정입니다 (번거롭지만, 매번 해 주어야 함).
  // 물론 response 대신 res 등으로 변수명은 바꾸어도 됩니다.
  fetch('data.json')
    .then(response => response.json())
    .then(datas => {
      // 배열의 요소 중, color 가, 사용자가 입력한 색과 일치하는 요소를 찾음. 
      const foundData = datas.find(data => data.color === userInputColor)
      
      // 찾은 요소는 객체인데, 그 value값이 헥사코드임.
      hexaCodeElem.innerHTML = foundData.value
      
      // 참고로, 아래 코드를 추가하면 색상도 반영됨.
      hexaCodeElem.style.color = foundData.value
    })
  
}

const inputElem = document.querySelector('#inputColor')
const buttonElem = document.querySelector('#buttonSubmit')
const hexaCodeElem = document.querySelector('#hexaCode')

buttonElem.addEventListener("click", showHexaCode)

 

반응형

+ Recent posts