Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Can get the array after assgin value in forEach Javascript

I am doing recommend system function but i meet a problem like below

const getProductRecommmend = asyncHandler(async (req, res) => {
  let arrMeasure = []
  
  const comparePromise = (desc) => {
    return new Promise((resolve,rejects) => {
      tfidf.tfidfs(desc,function (i,measure) {
        arrMeasure.push({
          index:i,
          measureProps:measure
        })
      })
      resolve(arrMeasure)
    })
  }



  const lastOrder = await (await Order.find({ user: req.user._id })).pop()
  const products = await Product.find({})
  // console.log(products)
  products.forEach(item => {
    tfidf.addDocument(item.description);
  })
  let arrResultMeasure = []
  
  lastOrder.orderItems.forEach(async(item) => {
    const product = await Product.findById(item.product).select('description')
    const resultMeasure = await comparePromise(product.description)  
    arrResultMeasure = [...resultMeasure]
    // console.log('arrResultMeasure',arrResultMeasure)
  })
  console.log('arr1',arrResultMeasure) // empty array
  res.json(lastOrder) 
})

When I console log arrResultMeasure inside forEach, it still log value, but when I console log outside of it, as you see in this below code, it return an empty array, I tried many way but it's still doesn't work.Does anyone have a solution to this problem? Thank you!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!