/**
* Synchronously executes a list of URL monitoring tasks.
*
* @param {Array<Object>} urlList An array of objects, where each object
* contains a 'url' property (string) and
* optional 'method' (string, e.g., 'GET', 'POST')
* and 'data' (object for POST requests).
* @returns {Promise<Array<Object>>} A promise that resolves with an array
* of results, one for each URL. Each result
* object will contain 'url', 'status', 'response', and 'error' properties.
* Rejects if any URL fails.
*/
async function synchronousUrlMonitoring(urlList) {
const results = [];
for (const item of urlList) {
try {
// Simulate synchronous execution. Replace with actual
// synchronous URL monitoring logic.
let response;
let error = null;
if (item.method === 'GET') {
response = await fetch(item.url); //Using await for consistency
} else if (item.method === 'POST') {
const body = JSON.stringify(item.data);
const response = await fetch(item.url, {
method: item.method,
headers: {
'Content-Type': 'application/json',
},
body: body,
});
} else {
error = new Error('Unsupported HTTP method');
}
if (!response.ok) {
error = new Error(`HTTP error! Status: ${response.status}`);
const errorText = await response.text(); //Get error content
error.message += `\nError Text: ${errorText}`;
}
const result = {
url: item.url,
status: response.status,
response: await response.text(), //Read content
error: error,
};
results.push(result);
} catch (err) {
// Handle any errors during URL processing
console.error(`Error monitoring URL ${item.url}:`, err);
throw err; //Re-throw to reject the entire promise
}
}
return results;
}
//Example Usage (replace with your actual URL list)
async function example() {
const urls = [
{ url: 'https://example.com', method: 'GET' },
{ url: 'https://httpstat.us/200', method: 'GET' },
{ url: 'https://httpstat.us/500', method: 'GET' },
{ url: 'https://httpstat.us/404', method: 'GET' },
{ url: 'https://httpstat.us/200', method: 'POST', data: { key: 'value' } },
];
try {
const monitoringResults = await synchronousUrlMonitoring(urls);
console.log(monitoringResults);
} catch (error) {
console.error('Monitoring failed:', error);
}
}
//example(); //Uncomment to run the example
Add your comment