Guest User

Untitled

a guest
Mar 19th, 2021
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function fetchRecursive(base_url, arr) {
  2.   const result = [];
  3.   const promises = [];
  4.  
  5.   if (Array.isArray(arr))
  6.     for (const n of arr) {
  7.       if (n.children) {
  8.         let ch_arr;
  9.         try {
  10.           const data = {
  11.             id: n.id,
  12.             externalId: n.externalId,
  13.             text: n.text,
  14.             children: fetch(base_url + n.id).then((r) => {
  15.               ch_arr = { ...r };
  16.               return r.json();
  17.             }),
  18.             productCount: n.productCount,
  19.           };
  20.          
  21.           data.children.then(children => data.children = children);
  22.           promises.push(data.children);
  23.  
  24.           result.push(data);
  25.         } catch (error) {
  26.           result.push({ id: n.id, error });
  27.         }
  28.         result.push(...(await fetchRecursive(base_url, ch_arr)));
  29.       } else {
  30.         result.push(n);
  31.       }
  32.     }
  33.  
  34.   await Promise.all(promises);
  35.   return result;
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment