[JavaScript] Promise, fetch 복습

hyxoo·2023년 4월 19일
0
post-thumbnail

📌 Promise

Promise는 비동기 처리에 사용되는 객체이다. Promise가 생성된 시점에는 정해지지 않았을 수 있는 결과를 나중에 돌려주겠다는 약속(promise)을 반환하는 것이다. 이는 콜백 함수의 단점을 보완할 수 있다.

✔️ Promise의 세가지 상태

  • 대기(pending): 이행하지도, 거부하지도 않은 초기 상태.
new Promise(function(resolve, reject) {
  // ...
});
  • 이행(fulfilled): 연산이 성공적으로 완료됨.
new Promise(function(resolve, reject) {
  resolve();
});
  • 거부(rejected): 연산이 실패함.
new Promise(function(resolve, reject) {
  reject();
});

✔️ Promise 결과 처리 메서드

  • then() : Promise가 성공적으로 해결되면 실행되며 결과를 인자로 받는다.
  • catch() : Promise가 거부되면 실행되며 에러를 인자로 받는다.

📎 Promise 사용해보기

function waitForTwoSeconds() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve("Waited for 2 seconds");
    }, 2000);
  });
}

console.log("Start");

waitForTwoSeconds()
  .then(function(result) {
    console.log(result);
  })
  .catch(function(error) {
    console.log(error);
  });

console.log("End");

❗️결과 출력

Start
End
Waited for 2 seconds

✔️ Promise Chaining

Promise chaining은 then() 메서드를 이용하여 연속적인 비동기 작업을 처리하는 방식이다. Promise chaining을 사용하면 각각의 비동기 작업을 순차적으로 실행하고, 이전 작업의 결과를 다음 작업에 전달할 수 있다.

function waitTwoSeconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('Waited for 2 seconds');
    }, 2000);
  });
}

waitTwoSeconds()
  .then(result => {
    console.log(result);
    return 'This is the next step';
  })
  .then(result => {
    console.log(result);
    return 'This is the final step';
  })
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  });

❗️결과 출력

Waited for 2 seconds
This is the next step
This is the final step

📌 fetch

fetch() 함수는 request, jQuery, axios 같은 라이브러리를 대신해 사용할 수 있는 브라우저 내장 함수중 하나로 네트워크를 통해 리소스를 가져오는 기능을 한다.

fetch() 함수는 Promise를 반환하며, 이 Promise는 HTTP 응답(Response)을 나타내는 Response 객체를 반환한다.

fetch()jQuery.ajax() 의 차이점

➡️ fetch()가 반환하는 Promise 객체는 404, 500과 같은 HTTP 오류 상태를 수신해도 거부되지 않고 .then을 통해 처리된다.

✔️ fetch의 기본 형태

fetch(url,options)
  .then((response) => response.json())
  .then((data) => console.log(data));
  .catch(error => console.error('Error:', error));

📎 fetch로 CRUD 구현하기

✔️ GET

fetch() 함수는 디폴트로 GET 방식으로 작동한다. GET은 요청 전문을 받지 않기 때문에 옵션 인자를 쓰지 않는다.

fetch(url)
  .then((response) => response.json())
  .then((data) => console.log(data));
  .catch(error => console.log(error));

위 방식으로 호출하면 response 객체로부터 JSON 포멧의 응답 전문을 자바스크립트 객체로 변환하여 얻을 수 있다.

✔️ POST

POST 요청을 보내기 위해서는, fetch() 함수의 두 번째 인자, 즉 옵션 인자로 요청에 대한 구성을 객체로 전달해야 한다. 객체의 속성으로는 method, headers, body 등을 설정할 수 있다.

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then((response) => response.json())
  .then((data) => console.log(data));
  .catch(error => console.log(error));

GET과 마찬가지로 응답 객체의 json() 메서드를 호출해서 응답 전문을 객체 형태로 얻을 수 있다.

✔️ PUT

PUT 요청은 주로 데이터를 수정해야 할 때 사용하며 POST와 유사하게 사용한다.

fetch(url, {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then((response) => response.json())
  .then((data) => console.log(data));
  .catch(error => console.log(error));

✔️ DELETE

DELETE 요청은 데이터를 삭제할 때 사용되며 보내는 데이터가 없다. 따라서 headerbody 옵션이 필요하지 않다.

fetch(url, {
  method: "DELETE",
)}
  .then((response) => response.json())
  .then((data) => console.log(data));
  .catch(error => console.log(error));
profile
hello world!

0개의 댓글