JavaScript Interview Question #89

How does fetch() work in JavaScript?

Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate

Quick Interview Answer

fetch starts an HTTP request and returns a Promise that fulfills with a Response object when an HTTP response is received. The response body can then be read with methods such as json, text, blob, or arrayBuffer.

Detailed Explanation

fetch starts an HTTP request and returns a Promise that fulfills with a Response object when an HTTP response is received. The response body can then be read with methods such as json, text, blob, or arrayBuffer.

An important interview point is that fetch does not reject merely because the server returns an HTTP error status such as 404 or 500. Code should check response.ok or response.status when such responses should be treated as failures.

Code Example

async function getProducts() {
    const response = await fetch("/api/products");

    if (!response.ok) {
        throw new Error(`Request failed: ${response.status}`);
    }

    return await response.json();
}