1. /**
  2. * Formats API responses with a timeout.
  3. * @param {Promise<any>} promise The promise to resolve or reject.
  4. * @param {number} timeoutMs The timeout in milliseconds.
  5. * @returns {Promise<any>} A promise that resolves with the formatted response or rejects with an error.
  6. */
  7. async function formatApiResponseWithTimeout(promise, timeoutMs) {
  8. return new Promise((resolve, reject) => {
  9. const timeoutId = setTimeout(() => {
  10. reject(new Error('API request timed out')); // Reject the promise if timeout occurs
  11. }, timeoutMs);
  12. promise
  13. .then(response => {
  14. // Format the response (e.g., pretty-print JSON)
  15. try {
  16. const formattedResponse = JSON.stringify(response, null, 2); // Pretty-print JSON
  17. resolve(formattedResponse); // Resolve with the formatted response
  18. } catch (error) {
  19. reject(new Error(`Error formatting response: ${error.message}`));
  20. } finally {
  21. clearTimeout(timeoutId); // Clear the timeout if the promise resolves
  22. }
  23. })
  24. .catch(error => {
  25. clearTimeout(timeoutId); // Clear the timeout if the promise rejects
  26. reject(error); // Reject the promise with the original error
  27. });
  28. });
  29. }

Add your comment