Reference article · Programming
Promises, async/await and fetch requests
Network requests take time and can fail. Promises represent future results, allowing other tasks to continue while a response arrives.
Promises and async functions
A promise can be pending, fulfilled or rejected. An async function returns a promise. await suspends that function until the result is available; it does not itself block the whole browser. Heavy computation still needs performance consideration.
Checking HTTP status
fetch returns a promise for a Response. HTTP 404 and 500 do not automatically reject it. response.ok covers status codes 200–299. response.json() is another asynchronous operation and can fail on invalid JSON.
Local file example
Create datos.json with the shown content and serve both files from the same local HTTP server, rather than opening with file://. This example expects JSON and does not suit a bodyless 204 response.
// datos.json: {"message":"Library ready"}
async function loadMessage() {
const response = await fetch("./datos.json");
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
}
loadMessage()
.then((data) => console.log(data.message))
.catch((error) => console.error("Could not load:", error));Requests to another origin
Browsers apply CORS to cross-origin requests. The destination server must allow the relevant access. mode: "no-cors" produces an opaque response rather than letting you read it freely. Check server documentation and configuration.
Check success and failure
- Load the valid file and check the message.
- Change the path to trigger a 404 and verify the error.
- Introduce invalid JSON and observe the parsing failure.
- In a real interface, provide understandable loading, success and error states.
References
Related articles
- Fundamentals: variables, conditions and loops
- Semantic HTML and page structure
- CSS: box model, Flexbox and Grid
- JavaScript: functions, parameters and scope
- JavaScript: arrays, objects and data transformations
- DOM and events: connect JavaScript to HTML
- HTTP and web APIs: requests, responses and status codes
- JSON: format, parsing and data validation
- Git: changes, commits, branches and remotes
- Node.js and npm: project scripts and dependencies
- Debugging and tests: finding and checking errors
- Colour formats: HEX, RGB and HSL
- UUID identifiers
- Random values in JavaScript
