How to get the result of callback?

Get data from DB, but since the search is performed, User data is synchronous, it does not work just return the result Kabaka in a variable. Tell me how can I solve this problem? Can you help?

let userRead = (userID) => {
 let userData;

 mongoose.connect(`${url}${database}`, optionsConnect);

 User.find({uid: userID}, (err, doc) => {
mongoose.disconnect();

 userData = doc; // Data from database
});

 return userData; // undefined
};
June 10th 19 at 14:24
2 answers
June 10th 19 at 14:26
Solution
Due to the fact that mongoose is asynchronous, doc will be written to userData after you return. Try to pass to the function userRead 2 parameters: userID and a callback function. And then instead of return you can simply call the function callback with the parameter doc and return her data.
Or just create a Promise
I think I understand what you're saying. And, apparently, the way I would like to use it (to pass to a variable and work with it anywhere in the code) doesn't work?

let userRead = (userID, cb) => {
 mongoose.connect(`${url}${database}`, optionsConnect);

 User.find({uid: userID}, (err, doc) => {
mongoose.disconnect();
cb(doc);
});
};

function callback(res) {
 console.log(res); // doc
}

let result = userRead(id, callback);
- Reina.Ward commented on June 10th 19 at 14:29
no , due to the fact that the number of asynchronous, we have to work with the callback and promise - Betty_Huels commented on June 10th 19 at 14:32
June 10th 19 at 14:28
let userRead = async (userID) => {

 mongoose.connect(`${url}${database}`, optionsConnect);

 return await User.find({ uid: userID }, (err, doc) => {
mongoose.disconnect();
 return doc;
});

};

Find more questions by tags Node.jsJavaScript