resolve(parent, args) {
let argumentCheck = (args.title && args.content && args.author_id);
let author_idCheck = false;
try {
if(argumentCheck == undefined) {
throw new Error("New article arguments are not defined!");
}
else {
console.log("ArgumentCheck passed!")
}
userModel_i.findById(args.author_id, (error, userObject)=>{
if(userObject !== undefined){
author_idCheck = true;
console.log(author_idCheck)
//If this is placed outside of callback then author_idCheck undefined
//Because code is asynchornous takes time for callback function run
//Therefore console.log run before callback finishes hence undefined
}
})
console.log("run")
let articleModel = new articleModel_i({
title: args.title,
content: args.content,
author_id: args.author_id, //Author ID should come from somewhere in applciation
createdAt: String(new Date())
})
return articleModel.save();
}
catch(e) { console.log(e) }
}
I have 2 blocks of code:
- The code inside the callback function for
findById
and - the code after
condole.log("run")
.
The callback function is taking time to run, so the console.log()
and code after runs first. The problem is the code after the condole.log("run")
depends on the code in the callback of code block 1, so the callback should be run first. I can't place the code after the console inside the callback because the return statement would then be for the callback and not the resolve function.
Is there any way to make the callback run first then the code after console? I'm thinking maybe passing them both inside a function and run them in there?