JavaScript Fetch API

Definition and usage

fetch() The method starts the process of retrieving resources from the server.

fetch() The method returns a Promise that is parsed as a Response object.

Tip:No longer need XMLHttpRequest.

Instance

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

Try it yourself

Fetch is based on async and await. This example may be easier to understand:

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

Try it yourself

Use easily understandable names instead of x and y:

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

Try it yourself

Syntax

fetch(file)

Parameter

Parameter Description
file Optional. The name of the resource to be retrieved.

Return value

Type Description
Promise Parse as Response object Promise.

Webbläsarstöd

fetch() Det är ECMAScript6 (ES6) egenskaper.

Alla moderna webbläsare stöder ES6 (JavaScript 2015).

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Ja Ja Ja Ja Ja

Internet Explorer 11 (och tidigare versioner) stöder inte fetch()