Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do you make synchronous HTTP request in JavaScript?
Making synchronous HTTP requests in JavaScript blocks code execution until the response arrives. While generally discouraged, certain scenarios may require this approach. This article explores methods to create synchronous HTTP requests in JavaScript.
Why Synchronous Requests?
Synchronous requests pause execution until completion, which can freeze the browser. However, they're sometimes needed for:
Critical data required before proceeding
Sequential API calls with dependencies
Legacy code compatibility
Algorithm
The basic steps for making synchronous HTTP requests:
Create an HTTP request object
Configure the request (method, URL, synchronous mode)
Send the request
Wait for the response
Handle the response or error
Using XMLHttpRequest (True Synchronous)
XMLHttpRequest supports true synchronous requests by setting the third parameter to false:
function synchronousRequest(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // false = synchronous
xhr.send(null);
if (xhr.status === 200) {
return xhr.responseText;
} else {
throw new Error('Request failed: ' + xhr.statusText);
}
}
Example
<html>
<body>
<script>
function synchronousRequest(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send(null);
if (xhr.status === 200) {
return xhr.responseText;
} else {
throw new Error('Request failed: ' + xhr.statusText);
}
}
try {
console.log('Before request');
const url = 'https://jsonplaceholder.typicode.com/todos/1';
const responseData = synchronousRequest(url);
console.log('Response:', JSON.parse(responseData).title);
console.log('After request');
} catch (error) {
console.error('Error:', error.message);
}
</script>
</body>
</html>
Before request Response: delectus aut autem After request
Using Async/Await (Synchronous-like)
Modern fetch API doesn't support true synchronous requests, but async/await provides synchronous-like behavior:
async function synchronousFetch(url) {
const response = await fetch(url);
if (response.ok) {
const data = await response.text();
return data;
} else {
throw new Error('Request failed: ' + response.statusText);
}
}
Example
async function fetchData() {
try {
console.log('Before request');
const url = 'https://jsonplaceholder.typicode.com/todos/1';
const response = await fetch(url);
const data = await response.json();
console.log('Response:', data.title);
console.log('After request');
} catch (error) {
console.error('Error:', error.message);
}
}
fetchData();
Before request Response: delectus aut autem After request
Comparison
| Method | True Synchronous | Browser Support | Blocks UI |
|---|---|---|---|
| XMLHttpRequest | Yes | Universal | Yes |
| Fetch + async/await | No (async) | Modern browsers | No |
Important Considerations
Performance: Synchronous requests block the main thread
User Experience: Browser becomes unresponsive during request
Modern Practice: Avoid synchronous requests in production
Conclusion
While synchronous HTTP requests are possible with XMLHttpRequest, they should be avoided due to poor user experience. Use async/await with fetch for better performance and maintainability in modern applications.
