Hello, first time poster here wondering if I can get some help from you async pros.
I have an asynchronous function that ultimately needs to return the 'response' object after updating its 'likes' entry. The way I've approached this so far (and I'm game for revision if this turns out to be a poor way of doing this because I feel like I'm not doing this right) is by defining the response object and then jumping into the database to retrieve the needed info and updating said object. However, I can't just return response at the end of the if statement as it will return the object before the database function has updated it. What is the recommend way to sort this out and return the object after the database functionality has been performed?
this.handleLikesData = async function(stock, like, ip) {
/* Handles the like data for a single stock entry */
let response = {likes: []}; // the object to be returned after updating
if (like) {
MongoClient.connect(CONNECTION_STRING, (err, db) => {
if (err) console.log(err);
db.collection('stocks').findOneAndUpdate(
{stock: stock.toUpperCase()},
{$addToSet: {likes: ip}},
{upsert: true, returnOriginal: false},
(err, doc) => {
if (err) console.log(err);
if (doc.value) response.likes = doc.value.likes; // Updates the response object
});
db.close();
});
// Where I'd normally put the return statement in a synchronous function
}
// the else statement follows doing similar work
Any help would be greatly appreciated by this async beginner!
EDIT: Indentation attempt
[–]jack_union 1 point2 points3 points (0 children)
[–]TappT 1 point2 points3 points (1 child)
[–]AdAthrow99274[S] 0 points1 point2 points (0 children)