Reputation: 3
I want to make a quick Util file which would contain multiple functions such as an user_id to his name. As the image under shows, I tried to save the value throughout the code but the variable "name" doesn't get affected inside the .then(user => {})
for some reasons
I tried returning directly the value without using variable to save it.
I debugged and code runs fine and it gets into the if(!user){}else{}
perfectly.
The user returned by Mongoose works and I can console log the user.username (Cannot return it, either can I save it to a variable, which is what i'm doing on the code under)
const User = require('../models/users')
exports.id2name = (id) => {
let name = 'none'
User.findOne({_id: id}).then(user => {
if (!user) {
name = 'Unknown'
} else {
name = user.username
}
}).catch(err => console.log(err))
return name
}
I don't get any errors on my console. It is returning 'none' as a result even if it gets into the else statement inside the mongoose request.
Upvotes: 0
Views: 124
Reputation: 1462
You are getting this result for asynchronous behaviours of JavaScript.
You can try this code for getting the desired result.
exports.id2name = async (id) => {
try{
let name = 'none'
const user = await User.findOne({_id: id});
if(user) {
name = user.username;
} else {
name = 'Unknown';
}
return name;
} catch(e) {
console.log(e);
}
}
Upvotes: 2
Reputation: 912
It's asynchronous return. I mean you may need to use callback, Promise or other asynchronous way to deal with it, for example:
const User = require('../models/users')
exports.id2name = (id, callback) => {
User.findOne({_id: id}).then(user => {
if (!user) {
callback(null, 'Unknown')
} else {
callback(null, user.username)
}
}).catch(callback)
}
or promise:
const User = require('../models/users')
exports.id2name = (id) => {
return new Promise((resolve, reject) => {
User.findOne({_id: id}).then(user => {
if (!user) {
resolve('Unknown')
} else {
resolve(user.username)
}
}).catch(reject);
});
}
Upvotes: 1