0

Im trying to push the results into a variable, the variable changes when I use the push but at the end of the function when I console the variable it shows the value initialized at the beginning of the function. It would be great if someone could solve this problem.

const getProductFilters = async (req, res) => {
      var result = [];
      await Product.findById(req.params.id)
        .then(async (val) => {
          await val.filterIds.forEach(
            async (item) =>
              await Filter.findById(item)
                .then(async (itm) => {
                  await itm.variableIds.forEach(async (val) => {
                    await Variable.findById(val)
                      .then((a) => {
                        console.log("1--", result);
                        !result.includes(a.name) ? result.push(a.name) : "";
                      })
                      .catch((err) => console.log(err));
                  });
                })
                .catch((err) => console.log(err))
          );
          console.log("2--", result);
        })
        .catch((err) => console.log(err));
    };

I'm getting this result:

2-- []
1-- []
1-- [ 'size' ]
1-- [ 'size', 'color' ]
1-- [ 'size', 'color' ]
Zero99
  • 1
  • 1
  • 1
    A couple of things. 1) You shouldn't be mixing `async/await` with `then` - it defeats the purpose of using `async/await`. 2) You can't `async` a `forEach`. – Andy Feb 18 '22 at 12:48
  • how can I refactor it. I did remove the async in the forEach and async/await I just left the then. It didnt work – Zero99 Feb 18 '22 at 13:09

0 Answers0