/**
* Formats API responses with a timeout.
* @param {Promise<any>} promise The promise to resolve or reject.
* @param {number} timeoutMs The timeout in milliseconds.
* @returns {Promise<any>} A promise that resolves with the formatted response or rejects with an error.
*/
async function formatApiResponseWithTimeout(promise, timeoutMs) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error('API request timed out')); // Reject the promise if timeout occurs
}, timeoutMs);
promise
.then(response => {
// Format the response (e.g., pretty-print JSON)
try {
const formattedResponse = JSON.stringify(response, null, 2); // Pretty-print JSON
resolve(formattedResponse); // Resolve with the formatted response
} catch (error) {
reject(new Error(`Error formatting response: ${error.message}`));
} finally {
clearTimeout(timeoutId); // Clear the timeout if the promise resolves
}
})
.catch(error => {
clearTimeout(timeoutId); // Clear the timeout if the promise rejects
reject(error); // Reject the promise with the original error
});
});
}
Add your comment