Empty Array Outside Mongoose Function [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I am trying to retrieve the data from multiple collections using mongoose schema and then send the respond back in JSON format. This is the code I have written.
function GetConnections_V2(req,res){
Connection.find({"user_id":"55006c36c30f0edc5400022d"})
.exec(function(err,connections){
var list = [];
var obj = new Object();
connections.forEach(function(connection){
obj.friend_id = connection.user_id_friend;
User.findById(connection.user_id_friend)
.exec(function(err,user){
if(user !== null) {
obj.friend_email = user.email;
obj.friend_details_id = user.details;
UserDetail.findById(user.details).exec(function (err, details) {
obj.firstname = details.firstname;
obj.lastname = details.lastname;
obj.image = details.image;
list.push(obj);
});
}
});
});
});
console.log(list);
res.send(list);
};
Now on executing this code. It is returning empty array. How do I resolve this problem ?

You are calling async functions inside for loop. That's why list is empty.
You can use async to solve this problem.
var async = require('async');
function GetConnections_V2(req,res){
Connection.find({"user_id":"55006c36c30f0edc5400022d"})
.exec(function(err,connections){
var list = [];
async.each(connections, function(connection, callback){
var obj = new Object();
obj.friend_id = connection.user_id_friend;
User.findById(connection.user_id_friend)
.exec(function(err,user){
if(user !== null) {
obj.friend_email = user.email;
obj.friend_details_id = user.details;
UserDetail.findById(user.details).exec(function (err, details) {
obj.firstname = details.firstname;
obj.lastname = details.lastname;
obj.image = details.image;
list.push(obj);
callback();
});
} else {
callback();
}
});
}, function(err){
return res.send(list);
});
};
}
Hope it helps you.

Related

How to return an object from a function that contains a Promise and a .then and how to get the returned value in another function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
how can i return an object from a function that contains a Promise and a .then; and how can i get the returned value from that function, in another function? Here is the function that contains the Promise and the object that i want to return is obj:
function searchdb(user, key){
var ok;
const list = new Promise(function (resolve, reject) {
MongoClient.connect(uri, function(err, db) {
var dbc = db.db("chat");
dbc.collection("chat_messages").find({$or: [ {user1: key, user2: user}, {user1: user, user2: key} ]}).toArray(function (err, result){
if(err) {
reject(err);
} else {
resolve(result);
}
if(result[0].user1 == key){
ok = 1;
}
else{
ok = 2;
}
});
db.close();
});
});
var obj = {};
list.then(result => {
if (ok == 1){
obj[result[0].user1] = result[0].user2_seen;
}else{
obj[result[0].user2] =result[0].user1_seen;
}
console.log(obj); <--------------- here its working
}).catch(err => console.log(err.message));
return obj;
}
And here is the function where i want to get the return:
function get(data){
suser = data[0]
obj = data[1];
for (var i in obj){
var key = Object.keys(obj[i])[0];
var a = searchdb(suser, key);
console.log(a); <-------------- here its not working
}
}
I just can't return and get the return from that function, everything else its working fine. Please help
In your main function at the top level return new promise and resolve it whenever obj promise is solved and store it in newVarible.
Then Use promise.all("newVarible") after that you'll be able to get values of obj after the promise is being resolved anywhere.

Is there a way to recieve return valuefrom async functions to non-async function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
Everything works just fine I'm just new to js and web programming and non-experienced with async functions. I had tried with Promises with then() and couldn't do it.
I'm trying to pass the data isbn number to data1 object
let isbn = "";
//
req.files.imageFile.mv(imageAddress, function (error) {
if (error) {
console.log("Couldn't upload the isbn image file.");
console.log(error);
} else {
console.log("Image file successfully uploaded!");
readText(imageAddress)
.then(isbnNumber => {
}).catch()
}
});
var data1 = {
bookName,
isbn,
};
From this async function that recognize text and parse it as i want
async function readText ( imageAddress ) {
await worker.load();
await worker.loadLanguage("eng");
await worker.initialize("eng");
const {
data: { text },
} = await worker.recognize( imageAddress );
console.log(text);
await worker.terminate();
//get the isbn number from readed text
let textArr = text.split("\n");
var isbnText = "";
var i;
for(i= 0; i < textArr.length; i++){
var str = textArr[i];
if (str.includes("ISBN")){
isbnText = textArr[i];
}
}
isbnText = isbnText.replace("ISBN", "");
let isbnNumber = isbnText.replace(/-/g, "");
isbnNumber = isbnNumber.replace(/\D/g, '')
console.log(isbnNumber);
return isbnNumber;
}
I want to equelize to isbn which is declared outside of the function
readText(imageAddress)
.then(isbnNumber => {
isbn = isbnNumber;
}).catch()

Array of Array Node js [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 5 years ago.
I'm doing an Api call to receive some data about the users i'm following.
And for the moment i receive something like that [[{obj1},{obj2}],[{obj3}]] and I want something like this [{obj1},{obj2},{obj3}]. Because one user can have more than one object.
getDashboard = function (req, res) {
User.findById(req.params.id, function (err, user) {
if (!user) {
res.send(404, 'User not found');
}
else {
var a = user.following;
var promises = a.map(function(current_value) {
return new Promise(function(resolve, reject) {
Receta.find({"user_id":current_value._id}, function (err, recetas) {
if(!err) {
resolve(recetas);
} else {
reject(err);
}
});
});
});
Promise.all(promises).then(function(allData) {
var proms = allData.map(function(value){
return value
});
res.send(proms);
}).catch(function(error) {
res.send(error);
});
}
});
};
You could use ES6 Spread
var data = [["one", "two"],["three"],["four","five"]];
result = [].concat(...data);
console.log(result);
Alternative in ES5 you could use reduce :
var data = [["one", "two"],["three"],["four","five"]];
var result = data.reduce(function(prev,curv){
return prev.concat(curv)
}, []);
console.log(result);
EDIT I'm not quite sure this is what the question was asking, but this was my interpretation
So you want to flatten out an array? Let's first build a function that takes a nested array and flattens it out a single level, like so:
function flatten(arr){
var result = [];
arr.forEach(element => (
result = result.concat(element);
));
return result;
}
Now, what if we have a 3D array, like [[["hi"]]]. Then, we need to flatten it multiple times. In fact, we can do this recursively.
Each time, we can check if it's an array using Array.isArray(), and if it is, flatten it before appending. We can program this recursively.
function flatten(arr){
var result = [];
arr.forEach(element => (
result = result.concat(Array.isArray(element) ? flatten(element) : element)
));
return result;
}
and that is our final answer. With that second function, we can see that flatten(["hi", ["there"]]) works.

getting async nodejs value from each callback calls [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
var async = require('async');
var square = function (id, callback) {
Business.prototype.getBusinessUser(id,function(userObject){
return callback(userObject);
});
};
async.eachSeries(findBusinessResult, function (businessObject, callback) {
//console.log("results from square");
var result = square(businessObject["id"] , function(result){
console.log(result);
});
callback(); // Alternatively: callback(new Error());
}, function (err,results) {
if (err) { throw err; }
console.log('Well done :-)!');
console.log(results);
});
Why does the result always become undefined: any help please.
async is reserved word in ES7 and might give you problem later, when it's implemented.
What you might want to consider is actually using async/await togheter with babel.
Some browser is starting to implement it already
var square = id =>
new Promise(rs =>
Business.prototype.getBusinessUser(id, rs)
)
async search() {
for (let businessObject of findBusinessResult) {
let result = await square(businessObject.id)
console.log(result)
}
}
I hope this will be a game changer solution for most ppl. This is making ASYC java callback into somthing which look like sync with effiecent callback handling. Its my three days of challange. [Callbacks][1] are indeed a a major challage in javacript and here is how to solve issue using promises .
install bluebird
npm install bluebird --save
//inyour code
var Promise = require('bluebird'); //yeah awsome bird indeed :)
function extendBusinessObjectPromise(id,element) {
return new Promise(function(resolve, reject) {
Business.prototype.getBusinessUser( id ,function(userObject){
var extend = require('util')._extend;
mergedJson = userObject;
elements = element;
extend({},elements);
extend(elements,mergedJson);
global.businesssWithUsers.push(elements); //sahred object
resolve(global.businesssWithUsers)
})
})
}
//NOW how do you i call the promise result inside a foreach loop and get its value returned as callback result. seem crazy idea :(
Person.prototype.getPersons = function(filter , callback) {
//this my own Bill count since i have one using one user account
global.businesssWithUsers = [];
models.PersonModel.findAll(filter_combined).then(function (findBusinessResult) {
global.businesssWithUsers = []
var extend = require('util')._extend;
var mergedJsonArray = [];
if (findBusinessResult==null) {
return callback(false,"no result found");
}
var promiseBusinessResult = null; //promise reslover :)
var findBusinessResult =JSON.parse(JSON.stringify(findBusinessResult));
findBusinessResult.forEach(function(eachElement) {
var id = element["userId"];
promiseBusinessResult = extendBusinessObjectPromise(id,element);
});
promiseBusinessResult.done(function(result){
callback(true,result); //pass the result to main function
});
}).catch(function (err) {
log.error(err["errors"][0]["message"])
callback(false,err["errors"][0]["message"])
return
})
}
Success at last. Cheers!

execute a for loop in node js

I have been trying to get the value of a variable after execution of a for loop in node js. But it is showing as undefined. But the same variable is getting the desired value when I call the variable in setTimeout function after 5000ms. I don't want to use setTimeout because it varies from user to user who uses my application.
The code with which I'm trying is
function getQuestions()
{
for(x=0;x<sevenQIDs.length;x++)
{
var query = connection.query('SELECT QUESTION, OP1, OP2, OP3, OP4, ANS FROM QUESTIONS WHERE QUESTION_ID="'+sevenQIDs[x]+'"', function(err,result,fields){
if(err){
throw err;
}
else{
var a = result[0];
var resTime = [], resAns = [];
resTime.length = 5;
resAns.length = 5;
a.resTime = resTime;
a.resAns = resAns;
sevenQues.push(a);
}
});
}
}
socket.on('socket1', function(text)
{
getQuestions();
console.log(sevenQues);
}
Here sevenQues is a global variable and I'm getting undefined in the console. But when I put this
setTimeout(function()
{
console.log(sevenQues);
},5000);
I'm getting the desired value. Please help me to resolve this issue and I heard of some async.js file which can do the foreach loop to send the desired output. But I'm unable to get this done. Anyhelp would be appreciated.
try this:
function getQuestions(callback)
{
for(x=0;x<sevenQIDs.length;x++)
{
var query = connection.query('SELECT QUESTION, OP1, OP2, OP3, OP4, ANS FROM QUESTIONS WHERE QUESTION_ID="'+sevenQIDs[x]+'"', function(err,result,fields){
if(err){
throw err;
}
else{
var a = result[0];
var resTime = [], resAns = [];
resTime.length = 5;
resAns.length = 5;
a.resTime = resTime;
a.resAns = resAns;
sevenQues.push(a);
if(x == sevenQIDs.length-1) callback();
}
});
}
}
socket.on('socket1', function(text)
{
getQuestions(function(){console.log(sevenQues)});
}

Categories

Resources