JavaScript Fetch API

The Fetch API interface allows web browsers to send HTTP requests to web servers.

No longer need XMLHttpRequest.

Browser Support

The numbers in the table indicate the first browser version that fully supports Fetch API:

Chrome IE Firefox Safari Opera
Chrome 42 Edge 14 Firefox 40 Safari 10.1 Opera 29
June 2011 August 2016 August 2015 March 2017 April 2015

Fetch API Example

The following example retrieves a file and displays the content:

Example

fetch(file)
.then(x => x.text())
.then(y => myDisplay(y));

Try It Yourself

Since Fetch is based on async and await, the example above may be easier to understand:

Example

async function getText(file) {
  let x = await fetch(file);
  let y = await x.text();
  myDisplay(y);
}

Try It Yourself

Even better: use names that are easy to understand instead of x and y:

Example

async function getText(file) {
  let myObject = await fetch(file);
  let myText = await myObject.text();
  myDisplay(myText);
}

Try It Yourself