Why I have different results for 'same' thing? [duplicate] - node.js

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I need to mention that I'm new to Node.js in general but I'm not sure why for the following code will give me different outputs in console for questions and allQuestions variable ?
var models = require('./models')(mongoose);
var query = models.Question.find({});
var questions = Array();
query.exec(function(err, allQuestions){
//catch the error;
questions = allQuestions;
console.log(allQuestions);
});
console.log(questions);
Output of questions variable will be only: Mongoose: questions.find({}) { fields: undefined } while allQuestions will contain all the questions from database.
I need to know why ?
Also I need that my question variable contains allQuestions from database.

Thats because query.exec() runs the function you passed as parameter asynchronously and the last line console.log(questions); will be executed before the callback is.
If you need the value of questions, then use another callback:
var models = require('./models')(mongoose);
var query = models.Question.find({});
var questions = Array();
query.exec(function(err, allQuestions){
//catch the error;
questions = allQuestions;
console.log(allQuestions);
done();
});
function done() {
console.log(questions);
// handle `questions` here ...
}

Related

Flutter : Function need to wait [duplicate]

This question already has an answer here:
How to wait for forEach to complete with asynchronous callbacks?
(1 answer)
Closed 1 year ago.
Here is my code
Future<List<Record>> getRecordElements() async {
int i=0;
String at;
var cont =0;
List<String> name= [];
var db = await FirebaseDatabase.instance.reference().child("Volunteers/"+widget.vname+"/Records");
db.once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
print(values);
values.forEach((key,values) async {
if(values["cont"]!=null){
//Few complicated operations
values.forEach((key,values) {
print(values);
if(key=="name"){
name.add(values);
}
});
});
});
print("name " + name.toString());
//few more operations
return items;
}
I have modified out irrelevent parts of the code.
Thing is, name is an array whose values are fetched from the database. Only after the array is set, can function proceed.
But what is happening is that name is being printed before it has been set. And hence the other operations after that are also being affected.
I need the fetching to finish first, and only then move ahead.
Please help
I think You Should fetch Your data at initializing stage i.e. you should create a function to fetch data from database and then call that function from initState

Access a variable outside of a promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am writing a steam bot and am trying to check, if one of the items in a trade is worth below 1 USD. I need to access the "pass" variable, but it never works. Can someone help?
var receive = offer.itemsToReceive;
var pass = true;
receive.forEach(function(id) {
var args = id.split(",");
market.getItemPrice("some app id", some item name).then(function(result) {
var json = JSON.parse(JSON.stringify(result)); // returns e.G $0.08
var price = parseFloat(json.median_price.substring(1));
if(price*100 < 100) {
pass = false;
}
});
});
This question is asked a lot, but hopefully explaining it in your own problem's terms will help you understand.
Your code should wait for any possibility of pass = false;, but it doesn't because you call a asynchronous function --- imagine the code immediately moves on after calling that. Your foreach function is immediately processed and the next line is called until .getItemPrice responds some time later.
So instead, to "wait" for all the results, you can do something like:
var receive = offer.itemsToReceive;
var pass = true;
var itemReceivePromises = receive.map(id=>{
var args = id.split(",");
return market.getItemPrice("some app id", some item name).then(function(result) {
var json = JSON.parse(JSON.stringify(result)); // returns e.G $0.08
var price = parseFloat(json.median_price.substring(1));
if(price*100 < 100) {
pass = false;
}
});
});
Promise.all(itemRecievePromises).then(results=>{
console.log('pass',pass);
});
However, you should pass the "pass" result back through the promise instead of using a higher scoped variable.

Can't return data from node.js function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm facing an issue when trying to retrieve data from a function in node.js. I am somewhat new to node and asynchronous programming, so I probably just overlooked something, but any help is appreciated. Here is the code:
function CallFunc1(col,row){
var GoogleSpreadsheet = require('google-spreadsheet');
var creds = require(Client-Secret Filepath);
var doc = new GoogleSpreadsheet(My Spreadsheet's ID);
doc.useServiceAccountAuth(creds, function (err) {
doc.getCells(1,{'min-row':row,'max-row':row,'min-col':col,'max-col':col}, function (err,resp){
var trv = resp[0];
global.trvf = trv.value
console.log(trvf);
return trvf
});
});
}
console.log(CallFunc1(2,3));
The problem is that when I run it, it returns the value "undefined." It prints the correct result in the console, but when trying to call any data from outside the function it doesn't seem to work.
I apologize if this has already been answered or if it's kinda a noob question.
Why don't you set a trvf variable before the function so it is automatically a global variable and then do trvf = trv.value and return trvf.

I am having issues with the array in nodejs [duplicate]

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 4 years ago.
Node.js code to extract all the links from the web page and store it in the variable that stores the data inside the scope of the function but not showing the data outside the scope of the function.
var ineed = require('ineed');
var url = require('get-urls');
var list = require('collections/list');
var fs = require('fs');
var arr = [];
ineed.collect.hyperlinks.from("https://energy.economictimes.indiatimes.com/rss/", function (err, response, result) {
var links = url(JSON.stringify(result)).toArray();
var str="/rss/";
for(var i = 0; i<links.length; i++){
if((links[i].search(str))>-1){
arr.push(links[i]);
}
}
console.log(arr);
// I am getting the output of the array here
})
//While printing the array I am not getting the output
console.log(arr);
You got noting in second console.log just because your code wich collect information run asynchronously and arr accepted any value after the first console.log executed. So either you rewrite your code on "clean" promises like
new Promise((resolve)=>ineed.collect.hyperlinks.from(
"https://energy.economictimes.indiatimes.com/rss/",
function (err, response, result) {
var links = url(JSON.stringify(result)).toArray();
var str="/rss/";
for(var i = 0; i<links.length; i++){
if((links[i].search(str))>-1){
arr.push(links[i]);
}
}
resolve(arr)
}
))
.then((arr)=>console.log(arr));
or convert to async/await function.

Populate an array with multiple mongo queries [duplicate]

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 5 years ago.
I'm having a problem with a callback mess.
In my nodejs app, I'm trying to get an array of JSON Objects returned by a mongoDB request. I don't know why, but it don't populate as I want.
I suspect a problem of asynchronous results/callback mess.
var fruits = ["Peach", "Banana", "Strawberry"];
var finalTab = [];
fruits.forEach(function(fruit) {
db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {
finalTab[fruit] = result;
console.log(result); // -> display the desired content
db.close();
if (err) throw err;
}));
});
console.log(finalTab); // -> []
Thanks by advance for help.
EDIT :
As I need all results returned by my db.collection...functions... I'm trying to add these async commands to a queue, execute it and get a callback function.
I think that async nodejs module can help.
Can someone tell me how to do this in a ForEach() ?
The line finalTab[fruit] = result; will not help because fruit there is not index. You need to use index in forEach() as follows -
var fruits = ["Peach", "Banana", "Strawberry"];
var finalTab = [];
fruits.forEach(function(fruit, index) {
db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {
finalTab[index] = result;
console.log(result); // -> display the desired content
db.close();
if (err) throw err;
}));
});
console.log(finalTab); // -> []

Resources