promise는 비동기 작업에 최종완료나 실패를 나타내는 객체이다.
비동기 작업을 처리시 작업이 성공과 실패를 표준화 된 then(result)/ catch(message)로 제공해준다.
비동기르 멀티로 실행 할 수 있다.
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);
});
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