0

I just learned about Promises and I'm trying to understand how to properly return a value from an async function. So, the basis behind what I'm trying to do is read an array from a json file and pass that item into a function to get the sum of all the values matching that title and return it.

I am getting a return value of undefined. I don't know if I explained it enough so here's the code in question.


async function getSumOfCategories(sheet,multipleSheets=true,print=false) {
  // const sums = {};
  var sums = new Map;
  try {
    const data = await fs.readFile(`./json/monthlycosts.json`, 'utf8');
    const settingsJSON = JSON.parse(data);
    settingsJSON.settings.forEach(async (setting) => {
      if (setting.title == "Expenses") {
        setting.settings.forEach(async (category) => {
          const sum = await getCategoryWith(category,sheet,multipleSheets,print);
          sums.set(category, sum);
          // sums[category] = await getCategoryWith(category,sheet,multipleSheets,print);
        });
      }
    });
  } catch (error) {
    console.log(error)
  }
  return Promise.resolve(sums);
}

The function should get the sum value from this function


async function getCategoryWith(title,sheet,multipleSheets=true,print=false) {
  
  var sum = 0;
  try {
    if (multipleSheets){
      const data = await fs.readFile(`./json/expenses.json`, 'utf8');
      var expensesJson = JSON.parse(data);
      expensesJson.forEach(async (month) => {
        if (month.title == `${sheet.title}_Expenses` || month.title.includes(sheet.title)) {
          month.expenses_for_the_month.forEach( (expense) => {
            if (expense.category.includes(title) || expense.category == title) {
                sum += expense.amount;
            }
        });
        }
      })
      
    } else {
      const data = await fs.readFile(`./json/${sheet.title}_Expenses.json`, 'utf8');
      var expensesJson = JSON.parse(data);
      expensesJson.expenses_for_the_month.forEach( (expense) => {
        if (expense.category.includes(title) || expense.category == title) {
          sum += expense.amount;
        }
      });
    }
  } catch (error) {
    console.log(error.red);
  }
  return Promise.resolve(sum.toFixed(2)); 
}
devdoesit
  • 51
  • 6

0 Answers0