I have a function like so:
createNewUser async (user) {
const newUser = new User();
newUser.name = user.name;
newUser.password = user.password;
let result = await newUser.save((err, data) => {
if (err) return err;
console.log(data);
return data;
})
console.log(result) // Undefined
}
The result return undefined and it run BEFORE the console.log(data) which very weird. Is there any way to get the result of newUser.save() either it be error or the data that successfully saved?
I have a function like so:
createNewUser async (user) {
const newUser = new User();
newUser.name = user.name;
newUser.password = user.password;
let result = await newUser.save((err, data) => {
if (err) return err;
console.log(data);
return data;
})
console.log(result) // Undefined
}
The result return undefined and it run BEFORE the console.log(data) which very weird. Is there any way to get the result of newUser.save() either it be error or the data that successfully saved?
Share Improve this question asked Jul 16, 2020 at 5:55 LeonAdviceLeonAdvice 1232 silver badges8 bronze badges 2- Does this answer your question? Mongoose await save – Rohit Ambre Commented Jul 16, 2020 at 6:02
- i saw that before posting this thread but I did not aware that I cannot put callback in there if I want to await it. – LeonAdvice Commented Jul 16, 2020 at 7:25
3 Answers
Reset to default 5You don't have to use callback if you want to use async/await
or promises
.
This moment is clearified in documentation.
So, correct code:
async createNewUser (user) {
const newUser = new User();
newUser.name = user.name;
newUser.password = user.password;
const result = await newUser.save();
console.log(result); // result
}
And if you need to proccess errors (what is strongly remended, but in your code error handler doesn't do anything), you can just wrap it into try/catch
:
async createNewUser (user) {
const newUser = new User();
newUser.name = user.name;
newUser.password = user.password;
try {
const result = await newUser.save();
console.log(result); // result
} catch (err) {
console.error("something goes wrong");
}
}
Since you're passing a callback to save
it will no longer return a promise so using await
doesn't work.
If you want it to return a promise then don't pass a callback and you can use try-catch
block for detecting errors:
const createNewUser = async (user) => {
const newUser = new User();
newUser.name = user.name;
newUser.password = user.password;
try {
const result = await newUser.save();
console.log(result);
} catch (err) {
console.log(err);
}
};
You can use this shortcode too. If you need you can enclose that function in try-catch block.
async createNewUser (user) {
const result = new User({
name: user.name,
password: user.password
});
console.log(await result.save())
}