Fetch Api

less than 1 minute read

FETCH API

비동기 통신인 XMLHTTPRequest에 보기 좋은 패턴을 적용한 방식이다.

Why?

비동기 데이터 통신에 XMLHTTPRequest 객체를 활용하는 것이 전통적인 방법이다. 하지만 최근에 비동기 요청이 더 복잡하고 증가되면서, 비동기 통신에 보기 좋은 패턴이 적용되었다. fetch api는 그 결과물이며 이를 활용한 웹 개발이 일반적이다.

장점

promise 패턴을 활용해서 종전 비동기 통신(XHR객체 활용)보다 동기적으로 동작하는 것처럼 보이는 코드를 구현할 수가 있다. 가독성 있는 코드라고 볼 수 있다.

[예시]

fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})  
  .then(function(response) {  
    return response.text();  
  })  
  .then(function(text) {  
    console.log('Request successful', text);  
  })  
  .catch(function(error) {  
    log('Request failed', error)  
  });

Categories:

Updated: