I am new to javascript, I am trying to pass the result of a nested function, down to the rest of the parent function ? maybe?
I have documents in one mongodb collection, and company info in another. So I am trying to pair them up like this part of the code, but it is not doing what I am trying to get done. I think I am clearly missing something about javascript and the way it functions.
data is a list of documents and their variables.
Data.find(arg_object, function (err, data){
if (err){
console.log(err);
}
else {
console.log("LENGTH", data.length)
for (i in data) {
Companies.find({_id: data[i]['_id']})
.then(companies => {
console.log("Company Name:")
console.log("NAME >>>> >>>> ", companies[0]['name']);
return companies
})
.catch(err => {
console.log(err);
})
search_reply = {
'_id': data[i]['_id'],
'title': data[i]['title'],
'url': data[i]['url'],
'release_date': data[i]['release_date'],
'document_date': data[i]['document_date'],
'name': companies[0]['name'],
}
answers[i] = search_reply
}
return res.json(answers);
}
})
You can either move all of your search_reply logic inside promise then callback. The other solution which could be easier is to use async/await for handling Promises. Let's first assume that your parent function is called getSearchResults, so based on that your code would look like:
async getSearchResults() {
for (i in data) {
try {
const companies = await Companies.find({
_id: data[i]['_id']
});
console.log("Company Name:")
console.log("NAME >>>> >>>> ", companies[0]['name']);
search_reply = {
'_id': data[i]['_id'],
'title': data[i]['title'],
'url': data[i]['url'],
'release_date': data[i]['release_date'],
'document_date': data[i]['document_date'],
'name': companies[0]['name'],
}
answers[i] = search_reply
} catch (err) {
console.log(err);
}
}
}