1. /**
  2. * Wraps JSON object processing with error handling and fallback.
  3. *
  4. * @param {any[]} data An array of JSON objects to process.
  5. * @param {function} processObject A function to process each JSON object.
  6. * @param {function} fallback A function to call if processing fails.
  7. * @returns {Promise<any[]>} A promise that resolves with the processed data or rejects on a critical error.
  8. */
  9. async function processBatchJson(data, processObject, fallback) {
  10. if (!Array.isArray(data)) {
  11. return fallback("Input must be an array."); // Fallback for invalid input
  12. }
  13. const results = [];
  14. for (const item of data) {
  15. try {
  16. if (typeof item !== 'object' || item === null) {
  17. console.warn("Skipping non-object item:", item);
  18. results.push(null); //Or handle non-object items as needed, e.g. skip them
  19. continue;
  20. }
  21. const processedItem = await processObject(item);
  22. results.push(processedItem);
  23. } catch (error) {
  24. console.error("Error processing item:", item, error);
  25. results.push(null); // Or handle errors differently, e.g., skip the item
  26. if (fallback) {
  27. try {
  28. const fallbackResult = await fallback(item, error); // Pass the original item and error to fallback
  29. results.push(fallbackResult);
  30. } catch (fallbackError) {
  31. console.error("Fallback failed:", fallbackError);
  32. results.push(null); // or handle the fallback failure
  33. }
  34. }
  35. }
  36. }
  37. return results;
  38. }

Add your comment