:projectDao.js
var mongoose = require("mongoose")
const Project = mongoose.model("Project")
exports.createProject = async(data) => {
data.m.projectModelId=data.m.projectModel.split(",")[0]
data.m.projectModelName=data.m.projectModel.split(",")[1]
delete data.m.projectModel
let project = new Project(data.m)
let flag1= false
let flag2=false
let flag3=false
await project.save(function (err) {
if (err) {
flag1 = false
return console.error(err)
}else{
flag1=true
return Promise.resolve(flag1)
}
})
console.log(flag1)
let formModels = new ProjectData(data.formModels)
await formModels.save(function (err) {
if (err) {
flag2 = false
return console.error(err)
}else{
return flag2=true
}
})
let tableModels = new ProjectData(data.tableModels)
await tableModels.save(function (err) {
if (err) {
flag3 = false
return console.error(err)
}else{
return flag3=true
}
})
if(flag1&flag2&&flag3){
return true
}
}
controller:
//api
exports.createProject = async (ctx) => {
const result = projectDao.createProject(ctx.request.body)
ctx.body = {
result
}
}
as above, I want to realize that there are multiple save methods in the same method, one of which is saved in one table and the other in another table. How to get the total results after executing multiple save methods at the same time, because async, await is an asynchronous method, the value of flag obtained outside is actually unchanged.
if the three save are sequentially related, that is, the id obtained after the successful storage of the first save is stored in the second save, how can I write it better?
exports.createProject =(data) => {
data.m.projectModelId=data.m.projectModel.split(",")[0]
data.m.projectModelName=data.m.projectModel.split(",")[1]
delete data.m.projectModel
let project = new Project(data.m)
project.save(function (err, info) {
if (err) {
console.error(err)
} else {
for(let i=0;i<data.formModels.length;iPP){
let formModel = new ProjectData({projectId:info._id,projectSubmoduleId:data.formModels[i]._id,createUserId:info.createUserId,createUserName:info.createUserName})
formModel.save(function (err,formData) {
if (err) {
return console.error(err)
}else{
return console.log(formData)
}
})
}
for(let i=0;i<data.tableModels.length;iPP){
let tableModel = new ProjectData({projectId:info._id,projectSubmoduleId:data.tableModels[i]._id,createUserId:info.createUserId,createUserName:info.createUserName})
tableModel.save(function (err,tableData) {
if (err) {
return console.error(err)
}else{
return console.log(tableData)
}
})
}
}
})
}