Promise

yunji·2023년 7월 26일
0

node js

목록 보기
9/9

Promise란

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

promise는 비동기 작업에 최종완료나 실패를 나타내는 객체이다.

promise를 쓰는 이유

  1. 비동기 작업을 처리시 작업이 성공과 실패를 표준화 된 then(result)/ catch(message)로 제공해준다.

  2. 비동기르 멀티로 실행 할 수 있다.

fetch 사용하기

const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response.blob();
  })
  .then((response) => {
    myImage.src = URL.createObjectURL(response);
  });

Return value

A Promise that resolves to a Response object.

.then(result) -> fetch 실행한 결과가 성공일 경우 then을 호출 하고 resutl로 실행결과 값을 반환 해 준다.

result 값은 promise이다.

.catch(message) -> fetch 실행 한 결과가 실패일 경우 catch를 호출 하고 message로 실패한 이유를 리턴해준다.

참고
https://developer.mozilla.org/en-US/docs/Web/API/fetch
https://www.youtube.com/watch?v=Sn0ublt7CWM

profile
웹 개발

0개의 댓글