fetch
Starts the process of fetching a resource from the network, returning a promise that resolves to a Response object
Syntax
fetch(input, init?)Parameters
| Parameter | Type | Description |
|---|---|---|
| input | string | URL | Request | The resource to fetch |
| init | RequestInit | Options for the request (method, headers, body, etc.) |
Return Value
A Promise that resolves to a Response object
Examples
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice' }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
try {
const res = await fetch('/api/slow', { signal: controller.signal });
console.log(await res.json());
} catch (err) {
if (err instanceof DOMException) console.log('Request aborted');
}Understanding fetch
The fetch method in JavaScript starts the process of fetching a resource from the network, returning a promise that resolves to a Response object. It belongs to the window object and is one of the most widely used methods for working with window values in modern JavaScript and TypeScript applications.
The method signature is fetch(input, init?). It accepts 2 parameters: input, init. When called, it returns a promise that resolves to a response object. Understanding when and how to use fetch() helps you write more expressive, readable code.
Common use cases for fetch include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like json-parse, json-stringify, promise-all, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for fetch is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
JSON.parseParses a JSON string, constructing the JavaScript value or object described by the string
JSON.stringifyConverts a JavaScript value to a JSON string, optionally replacing values or including only specified properties
Promise.allTakes an iterable of promises and returns a single promise that resolves when all of the input promises have resolved, or rejects when any input promise rejects
More Global / Window Methods
Other methods in the Global / Window object
Related Tools
More Global / Window Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.