0

How do I make the .create() function to wait for table to be filled before returning it. Because data returns undefined

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

exports.create = async function () {
  TemplateConstruct.find().then(function (constructs) {
    let table = []
    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().then(table.push(newconstruct))
    })
    console.log(table)
    return table
  })
  // return [ 'test' ]
}

working around this :

constructFactory.create().then(function (data) {
  console.log(data)
})
Nikhil Kinkar
  • 761
  • 8
  • 31
Lauden
  • 88
  • 1
  • 8

1 Answers1

1

Instead of chaining the promise via .then(), you can await it:

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

exports.create = async function () {
  const constructs = await TemplateConstruct.find();
  let table = [];

  for (const construct of constructs) {
    let newconstruct = new Construct();
    newconstruct.number = construct.number;
    newconstruct.name = construct.name;
    newconstruct.basePrice = construct.basePrice;
    newconstruct.baseMicrowave = construct.baseMicrowave;
    newconstruct.atomGain = construct.atomGain;
    await newconstruct.save();
    table.push(newconstruct);
  }

  console.log(table);
  return table;
};
Martin Adámek
  • 16,771
  • 5
  • 45
  • 64