JavaScript 기초-05

wonder1ng·2025년 3월 23일

풀스택 기초

목록 보기
9/13
  • async, await, fetch, then, restful api에 관한 내용이 책에 없어서 chatGPT의 응답 기록

11 async, await, Pormise

🚀 JavaScript의 async와 await 완벽 정리

async와 await는 비동기 코드를 더 읽기 쉽고, 동기 코드처럼 보이게 만드는 JavaScript의 기능입니다.


✅ 1. 비동기 프로그래밍이란?

JavaScript는 싱글 스레드로 동작하기 때문에, 네트워크 요청, 파일 읽기, 타이머와 같은 시간이 걸리는 작업을 동기적으로 실행하면 프로그램이 멈춰버릴 수 있습니다.

따라서 JavaScript에서는 비동기 처리를 위해 Promise를 사용하며, 이를 더 간결하게 쓰도록 async/await가 등장했습니다.


✅ 2. async와 await의 기본 개념

🔹 async 함수

  • async 키워드를 사용하면 함수가 항상 Promise를 반환합니다.
  • 함수 내부에서 await을 사용할 수 있습니다.
async function myFunction() {
    return "Hello, Async!";
}

myFunction().then(console.log); // "Hello, Async!"

✅ async 함수는 자동으로 Promise를 반환합니다.
✅ return "Hello"는 Promise.resolve("Hello")로 변환됩니다.


🔹 await 키워드

  • await 키워드는 async 함수 내부에서만 사용 가능합니다.
  • await은 Promise가 완료될 때까지 기다렸다가 결과 값을 반환합니다.
async function fetchData() {
    let data = await Promise.resolve("데이터를 가져왔어요!");
    console.log(data);
}

fetchData(); // "데이터를 가져왔어요!"

✅ await을 사용하면 Promise가 해결될 때까지 기다리고, 결과 값을 반환합니다.
✅ await을 사용하지 않으면 Promise 객체가 반환됩니다.


✅ 3. async/await를 활용한 비동기 코드

🔹 예제 1: setTimeout을 Promise로 변환하여 사용

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function run() {
    console.log("3초 후 메시지가 나옵니다...");
    await delay(3000); // 3초 대기
    console.log("3초 후 실행 완료!");
}

run();

✅ await delay(3000)이 실행될 때, 3초 동안 기다린 후 다음 코드가 실행됩니다.


🔹 예제 2: fetch()를 사용한 비동기 요청

async function fetchUser() {
    let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
    let user = await response.json();
    console.log(user);
}

fetchUser();

✅ await fetch(url)이 실행되면 네트워크 요청이 끝날 때까지 기다렸다가 결과를 반환합니다.
✅ .json()도 비동기 함수이므로 await을 붙여야 합니다.


✅ 4. async/await에서 try...catch를 사용한 예외 처리

비동기 코드에서는 오류가 발생할 가능성이 있습니다. try...catch를 사용하면 에러를 안전하게 처리할 수 있습니다.

async function fetchData() {
    try {
        let response = await fetch("https://invalid-url.com");
        if (!response.ok) throw new Error("HTTP 오류 발생!");
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("에러 발생:", error.message);
    }
}

fetchData();

✅ fetch()에서 에러가 발생하면 catch 블록에서 처리합니다.


✅ 5. Promise.then() vs async/await 비교

async/await이 등장하기 전에는 Promise.then() 체이닝을 사용하여 비동기 작업을 처리했습니다.

🔹 Promise.then() 방식

fetch("https://jsonplaceholder.typicode.com/users/1")
    .then(response => response.json())
    .then(user => console.log(user))
    .catch(error => console.error("에러 발생:", error));

🔹 async/await 방식 (더 간결하고 가독성이 좋음)

async function fetchUser() {
    try {
        let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
        let user = await response.json();
        console.log(user);
    } catch (error) {
        console.error("에러 발생:", error);
    }
}

fetchUser();

✅ async/await은 코드가 더 직관적이고, 가독성이 좋습니다.
✅ try...catch를 사용하면 에러 처리도 더 깔끔합니다.


✅ 6. await 병렬 처리 (Promise.all())

await을 여러 번 호출하면 각 요청이 순차적으로 실행됩니다. 만약 동시에 실행해야 한다면 Promise.all()을 사용하세요.

async function fetchParallel() {
    let userPromise = fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json());
    let postPromise = fetch("https://jsonplaceholder.typicode.com/posts/1").then(res => res.json());

    let [user, post] = await Promise.all([userPromise, postPromise]);

    console.log("사용자:", user);
    console.log("게시물:", post);
}

fetchParallel();

✅ Promise.all()을 사용하면 여러 개의 비동기 작업을 동시에 실행하여 성능을 개선할 수 있습니다.


✅ 7. await의 문제점과 주의사항

❌ 1) async 함수는 Promise를 반환

async function getValue() {
    return 10;
}

console.log(getValue()); // Promise { 10 }

✅ async 함수의 반환 값은 자동으로 Promise.resolve(값)이 됩니다.
✅ 만약 동기적인 값이 필요하다면 await을 사용해야 합니다.

async function getValue() {
    return 10;
}

async function printValue() {
    let value = await getValue();
    console.log(value); // 10
}

printValue();

❌ 2) await은 async 함수 내부에서만 사용 가능

await 키워드는 async 함수 내부에서만 사용할 수 있습니다.

// ❌ 오류 발생: SyntaxError: await is only valid in async functions
let value = await Promise.resolve(10);
console.log(value);

✅ 해결 방법: async 함수 내부에서 사용해야 합니다.

async function test() {
    let value = await Promise.resolve(10);
    console.log(value);
}

test();

❌ 3) await을 남용하면 성능이 저하될 수 있음

async function fetchSequential() {
    let user = await fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json());
    let post = await fetch("https://jsonplaceholder.typicode.com/posts/1").then(res => res.json());

    console.log("사용자:", user);
    console.log("게시물:", post);
}

✅ 이 방식은 첫 번째 요청이 끝나야 두 번째 요청이 시작되므로 비효율적입니다.
✅ Promise.all()을 사용하여 동시에 실행하는 것이 더 좋습니다.


🎯 정리

기능설명
async함수가 Promise를 반환하도록 만듦
awaitPromise가 완료될 때까지 기다림
try...catch에러를 처리하는 방법
Promise.all()여러 개의 비동기 작업을 병렬로 실행

async/await은 비동기 코드를 더 직관적이고 가독성 좋게 작성할 수 있는 강력한 기능입니다. 🚀

12 fetch, then

🚀 fetch와 then에 대한 상세 설명

JavaScript에서 fetch는 HTTP 요청을 보내는 내장 API이며, then은 비동기 처리(Promise)를 연결하는 메서드입니다.
이 두 개념은 함께 사용되는 경우가 많으며, 이를 이해하면 네트워크 요청과 비동기 처리를 쉽게 다룰 수 있습니다.


✅ 1. fetch란?

fetch는 서버에서 데이터를 가져오거나 보내기 위한 비동기 네트워크 요청을 수행하는 함수입니다.

  • Promise 기반이므로 결과를 기다려야 함
  • 기본적으로 GET 요청을 보냄
  • 응답을 JSON 등으로 변환해야 함

📌 기본 사용법 (GET 요청)

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(response => response.json()) // JSON 변환
    .then(data => console.log(data)) // 데이터 출력
    .catch(error => console.error("Error:", error)); // 오류 처리

✅ fetch()는 Promise를 반환하므로, .then()을 사용해야 결과를 처리할 수 있음.
✅ 응답 객체(Response)를 json()으로 변환해야 실제 데이터를 사용할 수 있음.


✅ 2. then이란?

then은 Promise의 결과를 처리하는 메서드로, 비동기 작업이 완료되었을 때 실행됩니다.

  • then(callback) 형태로 사용됨
  • 앞 단계의 Promise 결과를 받아 처리할 수 있음
  • 여러 개의 then()을 체이닝하여 순차 실행 가능

📌 then 기본 사용법

const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("완료!"), 2000); // 2초 후 성공
});

myPromise.then(result => console.log(result)); // "완료!" 출력

✅ resolve()가 실행되면 then()이 호출됨.
✅ setTimeout을 사용하여 비동기 작업(2초 후 실행)을 예제에 포함함.


✅ 3. fetch와 then의 관계

fetch는 Promise를 반환하기 때문에, then을 사용하여 결과를 처리해야 합니다.
이 과정에서 .then(response => response.json()) 같은 체이닝이 필요합니다.

📌 예제: fetch와 then의 조합

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(response => {
        console.log(response); // Response 객체 출력
        return response.json(); // JSON 변환
    })
    .then(data => {
        console.log(data); // 변환된 JSON 데이터 출력
    })
    .catch(error => {
        console.error("오류 발생:", error);
    });

✅ 첫 번째 then() → Response 객체 반환
✅ 두 번째 then() → JSON 데이터 변환 후 사용
✅ catch() → 오류 발생 시 처리


✅ 4. then 체이닝

여러 개의 비동기 작업을 순차적으로 실행할 때 then을 여러 개 연결할 수 있습니다.

📌 예제: 연속적인 요청 처리

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(response => response.json()) // 첫 번째 요청
    .then(post => {
        console.log("첫 번째 요청 결과:", post);
        return fetch(`https://jsonplaceholder.typicode.com/users/${post.userId}`);
    })
    .then(response => response.json()) // 두 번째 요청
    .then(user => {
        console.log("두 번째 요청 결과:", user);
    })
    .catch(error => console.error("오류 발생:", error));

✅ 첫 번째 fetch()로 게시글을 가져옴
✅ 두 번째 fetch()로 해당 게시글 작성자의 정보를 가져옴
✅ then을 체이닝하여 순차적으로 실행


✅ 5. fetch와 async/await 비교

fetch는 then을 사용하는 방식 외에도 async/await을 사용하여 더 간결하게 작성할 수 있습니다.

📌 예제: async/await 사용

async function fetchData() {
    try {
        const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("오류 발생:", error);
    }
}

fetchData();

✅ await을 사용하면 then 없이도 순차적으로 실행 가능
✅ try...catch를 사용하여 오류 처리

🚀 결론:

  • then()은 Promise를 처리하는 기본 방법
  • async/await은 then보다 더 읽기 쉬운 코드 작성 가능
  • 간단한 요청 → fetch + then,
    여러 개의 비동기 작업 → async/await 추천 ✅

🎯 정리

개념설명
fetch(url)서버에 HTTP 요청을 보내는 내장 함수 (Promise 반환)
then(callback)Promise가 완료되었을 때 실행되는 메서드
response.json()응답을 JSON으로 변환하는 메서드 (fetch에서 사용됨)
catch(callback)오류가 발생하면 실행되는 메서드
async/awaitthen을 대체하는 더 간결한 비동기 코드 방식

🚀 실무에서는 async/await을 추천하지만, fetch + then도 기본적으로 이해해야 합니다!

13 restful api

https://jsonplaceholder.typicode.com/posts는 JSONPlaceholder라는 무료 API 서비스에서 제공하는 더미 데이터입니다. 이 API를 사용하면 HTTP 요청을 통해 가짜 데이터를 받아오거나 보낼 수 있습니다. 예를 들어, GET 요청으로 게시글 데이터를 가져오거나 POST 요청으로 새 게시글을 추가할 수 있습니다.

다음은 fetch()를 사용하여 이 API에서 데이터를 가져오는 예제 코드입니다.

1. GET 요청을 통해 게시글 가져오기

// API에서 게시글을 가져오는 예제
fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    // 응답이 성공적이면 JSON 형식으로 변환
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data); // 가져온 게시글 데이터를 콘솔에 출력
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

2. POST 요청을 통해 새 게시글 추가하기

새 게시글을 추가하려면 POST 요청을 보내야 합니다. 이때 요청 본문에 JSON 데이터를 포함시켜야 합니다.

// 새 게시글을 추가하는 예제
const newPost = {
  title: 'New Post',
  body: 'This is a new post.',
  userId: 1,
};

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST', // POST 요청을 사용
  headers: {
    'Content-Type': 'application/json', // JSON 형식의 데이터를 보냄
  },
  body: JSON.stringify(newPost), // JSON 형식으로 바꿔서 보내기
})
  .then(response => response.json()) // 응답을 JSON 형식으로 변환
  .then(data => {
    console.log('New post created:', data); // 새로 생성된 게시글 출력
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

3. GET 요청으로 특정 게시글 가져오기

특정 게시글을 가져오려면 id를 URL에 포함시켜 요청을 보냅니다.

// 특정 게시글(id: 1)을 가져오는 예제
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => {
    console.log(data); // 게시글 데이터 출력
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

4. PUT 요청으로 게시글 업데이트하기

PUT 요청을 사용하여 기존 게시글을 업데이트할 수 있습니다.

// 게시글을 업데이트하는 예제
const updatedPost = {
  id: 1,
  title: 'Updated Post',
  body: 'This is an updated post.',
  userId: 1,
};

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PUT', // PUT 요청을 사용
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(updatedPost), // 업데이트된 게시글 데이터를 보내기
})
  .then(response => response.json())
  .then(data => {
    console.log('Updated post:', data); // 업데이트된 게시글 출력
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

5. DELETE 요청으로 게시글 삭제하기

DELETE 요청을 통해 게시글을 삭제할 수도 있습니다.

// 게시글을 삭제하는 예제
fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'DELETE', // DELETE 요청을 사용
})
  .then(() => {
    console.log('Post deleted');
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

결론

  • GET: 데이터를 가져옵니다.
  • POST: 새 데이터를 서버에 보냅니다.
  • PUT: 기존 데이터를 업데이트합니다.
  • DELETE: 데이터를 삭제합니다.

위의 코드들은 fetch() API를 사용하여 HTTP 요청을 보내는 방법을 보여줍니다. fetch()는 비동기적으로 작동하며, then() 메서드를 사용하여 응답을 처리하거나 catch()를 사용해 오류를 처리할 수 있습니다.

출처: chatGPT

profile
데이터, 풀스택

0개의 댓글