async / await

Siwoo Pak·2021년 7월 26일
0

Javascript

목록 보기
24/34

promise, fetch

const url = "https://jsonplaceholder.typicode.com/todos/1";
fetch(url)
  .then( res => res.json())
  .then( data => console.log(data))
  .catch( err => console.log(err));

async, await

const loadData = async () => {
  try {
    const url = "https://jsonplaceholder.typicode.com/todos/1";
    const res = await fetch(url);
    const data = await res.json();
    console.log(data);
    return data;
  } catch(err) {
    console.log(err);
  }
}

//const data = loadData().then(data=>console.log(data));

( async() => {
  const data = await loadData();
  console.log(data);
})();

promise.all

const url = "https://jsonplaceholder.typicode.com/todos/1";
const url2 = "https://jsonplaceholder.typicode.com/todos/2";
const url3 = "https://jsonplaceholder.typicode.com/todos/3";

const loadData = async () => {
  try {
    const res1 = await fetch(url);
    const data1 = await res1.json();
    const res2 = await fetch(url);
    const data2 = await res2.json();
    const res3 = await fetch(url);
    const data3 = await res3.json();
    console.log(data);
    return [data1, data2, data3];
  } catch(err) {
    console.log(err);
  }
}

( async() => {
  const data = await loadData();
  console.log(data);
})();
  • use promise.all
const url = "https://jsonplaceholder.typicode.com/todos/1";
const url2 = "https://jsonplaceholder.typicode.com/todos/2";
const url3 = "https://jsonplaceholder.typicode.com/todos/3";

const loadData = async () => {
  try {
    const results = await Promise.all([
    	fetch(url), fetch(url2), fetch(url3)
    ]);
    //const dataPromises = results.map(result => result.json());
    //const finalData = await Promise.all(dataPromises);
    const findalData = await Promise.all(results.map(result => result.json()));
    return finalData;
  } catch(err) {
    console.log(err);
  }
}

( async() => {
  const data = await loadData();
  console.log(data);
})();

문법
https://developers.google.com/web/fundamentals/primers/async-functions

참고: Tips For Using Async/Await in JavaScript

profile
'하루를 참고 인내하면 열흘을 벌 수 있고 사흘을 참고 견디면 30일을, 30일을 견디면 3년을 벌 수 있다.'

0개의 댓글