如何使.create()
函数在返回表之前等待表被填充。
因为data
返回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' ]
}
解决此问题:
constructFactory.create().then(function (data) {
console.log(data)
})
答案 0 :(得分:1)
您可以.then()
来代替通过await
链接诺言:
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;
};