/**
* Wraps JSON object processing with error handling and fallback.
*
* @param {any[]} data An array of JSON objects to process.
* @param {function} processObject A function to process each JSON object.
* @param {function} fallback A function to call if processing fails.
* @returns {Promise<any[]>} A promise that resolves with the processed data or rejects on a critical error.
*/
async function processBatchJson(data, processObject, fallback) {
if (!Array.isArray(data)) {
return fallback("Input must be an array."); // Fallback for invalid input
}
const results = [];
for (const item of data) {
try {
if (typeof item !== 'object' || item === null) {
console.warn("Skipping non-object item:", item);
results.push(null); //Or handle non-object items as needed, e.g. skip them
continue;
}
const processedItem = await processObject(item);
results.push(processedItem);
} catch (error) {
console.error("Error processing item:", item, error);
results.push(null); // Or handle errors differently, e.g., skip the item
if (fallback) {
try {
const fallbackResult = await fallback(item, error); // Pass the original item and error to fallback
results.push(fallbackResult);
} catch (fallbackError) {
console.error("Fallback failed:", fallbackError);
results.push(null); // or handle the fallback failure
}
}
}
}
return results;
}
Add your comment