1. /**
  2. * Synchronously executes a list of URL monitoring tasks.
  3. *
  4. * @param {Array<Object>} urlList An array of objects, where each object
  5. * contains a 'url' property (string) and
  6. * optional 'method' (string, e.g., 'GET', 'POST')
  7. * and 'data' (object for POST requests).
  8. * @returns {Promise<Array<Object>>} A promise that resolves with an array
  9. * of results, one for each URL. Each result
  10. * object will contain 'url', 'status', 'response', and 'error' properties.
  11. * Rejects if any URL fails.
  12. */
  13. async function synchronousUrlMonitoring(urlList) {
  14. const results = [];
  15. for (const item of urlList) {
  16. try {
  17. // Simulate synchronous execution. Replace with actual
  18. // synchronous URL monitoring logic.
  19. let response;
  20. let error = null;
  21. if (item.method === 'GET') {
  22. response = await fetch(item.url); //Using await for consistency
  23. } else if (item.method === 'POST') {
  24. const body = JSON.stringify(item.data);
  25. const response = await fetch(item.url, {
  26. method: item.method,
  27. headers: {
  28. 'Content-Type': 'application/json',
  29. },
  30. body: body,
  31. });
  32. } else {
  33. error = new Error('Unsupported HTTP method');
  34. }
  35. if (!response.ok) {
  36. error = new Error(`HTTP error! Status: ${response.status}`);
  37. const errorText = await response.text(); //Get error content
  38. error.message += `\nError Text: ${errorText}`;
  39. }
  40. const result = {
  41. url: item.url,
  42. status: response.status,
  43. response: await response.text(), //Read content
  44. error: error,
  45. };
  46. results.push(result);
  47. } catch (err) {
  48. // Handle any errors during URL processing
  49. console.error(`Error monitoring URL ${item.url}:`, err);
  50. throw err; //Re-throw to reject the entire promise
  51. }
  52. }
  53. return results;
  54. }
  55. //Example Usage (replace with your actual URL list)
  56. async function example() {
  57. const urls = [
  58. { url: 'https://example.com', method: 'GET' },
  59. { url: 'https://httpstat.us/200', method: 'GET' },
  60. { url: 'https://httpstat.us/500', method: 'GET' },
  61. { url: 'https://httpstat.us/404', method: 'GET' },
  62. { url: 'https://httpstat.us/200', method: 'POST', data: { key: 'value' } },
  63. ];
  64. try {
  65. const monitoringResults = await synchronousUrlMonitoring(urls);
  66. console.log(monitoringResults);
  67. } catch (error) {
  68. console.error('Monitoring failed:', error);
  69. }
  70. }
  71. //example(); //Uncomment to run the example

Add your comment