상세 컨텐츠

본문 제목

자바스크립트 비동기 프로그래밍 2편

JavaScript

by nata_developer 2020. 8. 7. 17:09

본문

*Udemy의  The Complete JavaScript Course 2020: Build Real Projects! 참고

 

1.PROMISE

const getIDs = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve([523, 883, 432, 974]);
  }, 1500);
});

const getRecipe = (recID) => {
  return new Promise((resolve, reject) => {
    setTimeout(
      (ID) => {
        const recipe = { title: "Fresh tomato pasta", publisher: "Jonas" };
        resolve(`${ID}: ${recipe.title}`);
      },
      1500,
      recID
    );
  });
};

const getRelated = (publisher) => {
  return new Promise((resolve, reject) => {
    setTimeout(
      (pub) => {
        const recipe = { title: "Italian Pizza", publisher: "Jonas" };
        resolve(`${pub}: ${recipe.title}`);
      },
      1500,
      publisher
    );
  });
};

getIDs
  .then((IDs) => {
    console.log(IDs);
    return getRecipe(IDs[2]);
  })
  .then((recipe) => {
    console.log(recipe);
    return getRelated("Jonas Schmedtmann");
  })
  .then((recipe) => {
    console.log(recipe);
  })
  .catch((error) => {
    console.log("Error!!");
  });

Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.

 

Promise는 다음 중 하나의 상태를 가집니다.

 

대기(pending): 이행하거나 거부되지 않은 초기 상태.

 

이행(fulfilled): 연산이 성공적으로 완료됨.

 

거부(rejected): 연산이 실패함.

 

참고-https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise

 

Promise

Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.

developer.mozilla.org

 

2.ASYNC

async function getRecipesAW() {
  const IDs = await getIDs;
  console.log(IDs);
  const recipe = await getRecipe(IDs[2]);
  console.log(recipe);
  const related = await getRelated("Jonas Schmedtmann");
  console.log(related);

  return recipe;
}

getRecipesAW().then((result) => console.log(`${result} is the best ever!`));

async function 선언은 AsyncFunction객체를 반환하는 하나의 비동기 함수를 정의합니다.

 

비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 

 

암시적으로 Promise를 사용하여 결과를 반환합니다.

 

참고-https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/async_function

 

async function

async function 선언은 AsyncFunction객체를 반환하는 하나의 비동기 함수를 정의합니다. 비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 암시적으로 Promise를 사용하여 결과를 반환

developer.mozilla.org

 

3.AJAX & API

function getWeather(woeid) {
    fetch(`https://crossorigin.me/https://www.metaweather.com/api/location/${woeid}/`)
    .then(result => {
        // console.log(result);
        return result.json();
    })
    .then(data => {
        // console.log(data);
        const today = data.consolidated_weather[0];
        console.log(`Temperatures today in ${data.title} stay between ${today.min_temp} and ${today.max_temp}.`);
    })
    .catch(error => console.log(error));
}

getWeather(2487956);
getWeather(44418);

async function getWeatherAW(woeid) {
  try {
    const result = await fetch(
      `https://crossorigin.me/https://www.metaweather.com/api/location/${woeid}/`
    );
    const data = await result.json();
    const tomorrow = data.consolidated_weather[1];
    console.log(
      `Temperatures tomorrow in ${data.title} stay between ${tomorrow.min_temp} and ${tomorrow.max_temp}.`
    );
    return data;
  } catch (error) {
    alert(error);
  }
}
getWeatherAW(2487956);

fetch

fetch()를 불러들이는 경우, 취득할 리소스를 반드시 인수로 지정하지 않으면 안됩니다.

읽어들인 뒤,  fetch()는 Promise객체를 반환합니다.

 

리퀘스트가 성공하든 실패하든 해당 리퀘스트 통신에 대한 Response객체가 취득됩니다. 

fetch()의 두번째 인수는 초기화에 사용되는 객체를 정의하고 있습니다. 

 

이 인수는 기입하지 않아도 함수의 동작에 문제가 없습니다.

이 인수에 대한 상세한 정보는 Request)를 참고해주시기 바랍니다.

 

참고-https://developer.mozilla.org/ko/docs/Web/API/Fetch_API

 

Fetch API

Fetch API는 네트워크 통신을 포함한 리소스 취득을 위한 인터페이스가 정의되어 있습니다.  XMLHttpRequest와 같은 비슷한 API가 존재합니다만, 새로운 Fetch API는 좀더 강력하고 유연한 조작이 가능��

developer.mozilla.org

 

'JavaScript' 카테고리의 다른 글

budgety app 1편  (0) 2020.09.15
자바스크립트 중간중간 모르는 것들!  (0) 2020.08.07
자바스크립트 비동기 프로그래밍 1편  (0) 2020.08.07
자바스크립트 ES6 4편  (0) 2020.08.07
자바스크립트 ES6 3편  (0) 2020.08.07

관련글 더보기