猫鼬的NodeJS异步功能

时间:2018-11-11 18:06:06

标签: javascript node.js async-await

如何使.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)
})

1 个答案:

答案 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;
};