1

I have been racking my brain for a couple of hours now, I hope you can help me!

const Construct = require('../models/constructModel')
const TemplateConstruct = require('../models/constructTemplateModel')

exports.create = function () {
  let universeConstructs = TemplateConstruct.get(async function (err, constructs) {
    if (err) {
      return false
    } else {
      let table = []
      await constructs.forEach((construct) => {
        let newconstruct = new Construct()
        newconstruct.number = construct.number
        newconstruct.name = construct.name
        newconstruct.basePrice = construct.basePrice
        newconstruct.baseMicrowave = construct.baseMicrowave
        newconstruct.atomGain = construct.atomGain
        newconstruct.save(function (err) {
          if (err) {
            return false
          } else {
            table.push(newconstruct)
          }
        })
      })
      console.log('table : ' + table)
      return table
    }
  })
  console.log('constructs : ' + universeConstructs)
  return universeConstructs
}

Neither the console.log table or constructs returns a what I expect.

constructs : undefined
table : 
Lauden
  • 88
  • 1
  • 8
  • `TemplateConstruct.get()` and `newconstruct.save()` are asynchronous? Make sure you get them to return promises instead of taking callbacks. – Bergi Nov 10 '18 at 17:51
  • They are mongoose function of find and save – Lauden Nov 11 '18 at 16:56
  • In that case, just omit the callback and they should return promises. `const universeConstructs = await TemplateConstruct.get();` and `return newconstruct.save();` – Bergi Nov 11 '18 at 17:01
  • I want to add my construct to an array, and I can't iterate on universeConstructs ... – Lauden Nov 11 '18 at 17:49
  • (`universe`)`constructs` should be the result value of the `TemplateConstruct.get()` promise, sure you can iterate that. See the duplicate question for how to do something asynchronous in the body of the iteration. – Bergi Nov 11 '18 at 17:57

0 Answers0