본문으로 바로가기

Promise 에 대한 공부 및 정리

category JS/JavaScript 2018. 2. 8. 14:15

// 아래 설명을 바탕으로 한 예제 입니다.
// https://developers.google.com/web/fundamentals/primers/promises

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        console.log('resolve :' + url);
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function getJSON(url) {
	console.log('getJSON : ' + url);
  return get(url).then(JSON.parse).catch(function(err) {
    console.log("getJSON failed for", url, err);
    throw err;
  });
}
function addHtmlToPage(html){
  console.log('addHtmlToPage : ' + html.id);
	var strParse = JSON.stringify(html);
	document.getElementById('contents').innerHTML += '

' + strParse + '

'; } // Start off with a promise that always resolves var story = {}; story.chapterUrls = ['https://jsonplaceholder.typicode.com/posts/1' ,'https://jsonplaceholder.typicode.com/posts/2' ,'https://jsonplaceholder.typicode.com/posts/3']; var sequence = Promise.resolve(); // 루프자체는 비동기가 아님 // 루프를 돌며 각각의 프롬미스를 생성 // 루프를 돌며 getJSON 함수를 바로 실행하는것이 아니라 // 프로미스만 리턴해주기 때문에 // 각각의 비동기 작업이 순서대로 진행 /* // Loop through our chapter urls story.chapterUrls.forEach(function(chapterUrl) { // Add these actions to the end of the sequence console.log('chapterUrl : ' + chapterUrl); sequence = sequence.then(function() { console.log('getJSON Call : ' + chapterUrl); return getJSON(chapterUrl); }).then(function(chapter) { console.log('addHtmlToPage Call : ' + chapter); addHtmlToPage(chapter); }); console.log('sequence : ' + sequence); }); */ // 루프자체는 비동기가 아님 // getJSON함수는 비동기처리 되나 /// 루프를 돌때 getJSON 함수를 바로 호출 하기 때문에 리턴순서가 꼬임 story.chapterUrls.forEach(function(chapterUrl) { console.log('chapterUrl : ' + chapterUrl); // Fetch chapter getJSON(chapterUrl).then(function(chapter) { // and add it to the page console.log('addHtmlToPage Call : ' + chapter); addHtmlToPage(chapter); }); });