JavaScript Fetch API
Examples
fetch(file)
.then(x => x.text())
.then(y => myDisplay(y));
Try it Yourself »
.then(x => x.text())
.then(y => myDisplay(y));
Fetch is based on async and await. The example might be easier to understand like this:
async function getText(file) {
let x = await fetch(file);
let y = await x.text();
myDisplay(y);
}
Try it Yourself »
let x = await fetch(file);
let y = await x.text();
myDisplay(y);
}
Use 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 »
let myObject = await fetch(file);
let myText = await myObject.text();
myDisplay(myText);
}
Description
The fetch()
method starts the process of fetching a resource from a server.
The fetch()
method returns a Promise that resolves to a Response object.
😀 No need for XMLHttpRequest anymore.
Syntax
fetch(file)
Parameters
Parameter
Description
file
Optional.
The name of a resource to fetch.
The name of a resource to fetch.
Return Value
Type
Description
Promise A Promise that resolves to a Response object.
Browser Support
fetch()
is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is supported in all browsers since June 2017:
Chrome 51 |
Edge 15 |
Firefox 54 |
Safari 10 |
Opera 38 |
May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |