Simple fetch polyfill for interview explanation using Promise & XMLHttpRequest.
// Simple fetch polyfill for interview explanation
if (!window.fetch) {
window.fetch = function(url, options = {}) {
return new Promise(function(resolve, reject) {
// Create XMLHttpRequest instance
const xhr = new XMLHttpRequest();
// Extract method and headers from options
const method = options.method || 'GET';
const headers = options.headers || {};
const body = options.body || null;
// Open the request
xhr.open(method, url, true);
// Set request headers if provided
for (let header in headers) {
xhr.setRequestHeader(header, headers[header]);
}
// Handle response
xhr.onload = function() {
// Create a Response-like object
const response = {
status: xhr.status,
ok: xhr.status >= 200 && xhr.status < 300,
text: function() {
return Promise.resolve(xhr.responseText);
},
json: function() {
return Promise.resolve(JSON.parse(xhr.responseText));
}
};
if (response.ok) {
resolve(response);
} else {
reject(new Error(`HTTP error! Status: ${xhr.status}`));
}
};
// Handle network errors
xhr.onerror = function() {
reject(new Error('Network error occurred'));
};
// Send the request
xhr.send(body);
});
};
}
// Example usage for interview demo
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Response not OK');
})
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('Error:', error.message);
});
Top comments (0)