Search code examples
reactjsasync-awaites6-promise

getting child categories base on parent category id using promises


Understanding: my little understanding with promise is we can use it in place of callback functions.

Scenario: i will fetch parent categories from api than pass the categories array of objects to a function, a promise function may be ?

const getData = async () => {
    const res = await fetch('API/categories?parent=0');
    const data = await res.json();
    return Promise.all(data.map(item => anAsyncFunction(item)))
}

this function recieves all the categories and i pass it to promise function

const anAsyncFunction = async item => {

    return functionWithPromise(item)
}

this returns right data all child categories in array of objects

const functionWithPromise = async data => { //a function that returns a promise
    const res = await fetch('API/categories?parent='+data.id);
    const datas = await res.json();
    // console.log(datas);
    
    // api call to insert all the records
    return Promise.resolve(data)
    
}

enter image description here

now i want to go through all these arrays and insert into database using api call

await api.create(postData)

Solution

  • You can merge anAsyncFunction & functionWithPromise functions. Two functions are unnecessary.

    The line return Promise.resolve(data) can be return data

    getData is thenable which gives you array of promise responses. Loop thru it twice and use Promise.all

    const getData = async () => {
      const res = await fetch("API/categories?parent=0");
      const data = await res.json();
      return Promise.all(data.map((item) => anAsyncFunction(item)));
    };
    
    const anAsyncFunction = async (data) => {
      const res = await fetch("API/categories?parent=" + data.id);
      const datas = await res.json();
      // api call to insert all the records
      //   return Promise.resolve(data);
      return datas;
    };
    
    getData().then((res) => {
      let promises = [];
      res.forEach((datas) => { //this loop is for each and every response
        datas.forEach((postData) => { //this loop is for
          promises.push(api.create(postData));
        });
      });
      Promise.all(promises).then((finalRes) => {
        console.log("finalRes", finalRes);
      });
    });