This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to make a function wait until a callback has been called using node.js
(11 answers)
Closed 5 years ago.
I'm learning node.js and I have a problem. How to get data from function to variable?
function loadOrInitializeTaskArray(file, cb) {
fs.exists(file, function(exists) {
var tasks = [];
if (exists) {
fs.readFile(file, 'utf8', function(err, data) {
if (err) throw err;
var data = data.toString();
var tasks = JSON.parse(data || '[]');
cb(tasks);
})
} else {
cb([]);
}
})
}
function listTasks(file) {
loadOrInitializeTaskArray(file, function(tasks) {
for (var i in tasks) {
console.log(tasks[i]);
}
})
}
Function listTasks works correctly, but I would like create own function, for example customListTasks:
function customListTasks(file) {
var list = loadOrInitializeTaskArray(file, function(){});
console.log(list);
}
This not return me errors, but console.log on list return me "undefined". How can I get this data to variable list?
Short answer: you can not.
Because the loading in loadOrInitializeTaskArray is asynchronous, all the magic has to happen in the callback that you are passing. You cannot just 'return' a value from it.
Option 1: Place all logic that depends on the loaded data in the anonymous function that you pass as callback.
var list = loadOrInitializeTaskArray(file, function(tasks){
console.log(tasks);
});
Option 2: Use Promises. They work essentially like callbacks, but are slightly more flexible and make chaining easier.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Hello could someone inform me how do I return the value of a query to use in another class This is my query:
var pconn = require('./db.js');
var dadosMsg = null
function getValueMsg(){
pconn.pool.query('SELECT b.numero_serie, b.grupo_msg, b.index_msg, b.valor_msg FROM bor_msg b LIMIT 1', (err, rows) => {
if (!err) {
dadosMsg = rows.rows[0];
return dadosMsg;
} else {
return err;
console.log(err);
}
});
}
I would like to return the query value in this class
var x = require('./dbmsg');
x.getValueMsg();
console.log(x.dadosMsg.valor_msg);
You can use Promise.
A Promises are used to handle asynchronous operations in JavaScript
Promise constructor takes only one argument,a callback function.
Callback function takes two arguments, resolve and reject
Perform operations inside the callback function and if everything went well then call resolve.
If desired operations do not go well then call reject.
function getValueMsg() {
return new Promise((resolve, reject) => {
pconn.pool.query('SELECT b.numero_serie, b.grupo_msg, b.index_msg, b.valor_msg FROM bor_msg b LIMIT 1', (err, rows) => {
if (!err) {
dadosMsg = rows.rows[0];
resolve(dadosMsg);
} else {
console.log(err);
reject(err);
}
});
});
}
// other file
var x = require('./dbmsg');
//You can consume Promises using then and .catch methods.
x.getValueMsg().then((results)=>{
console.log(results);
}).catch((err)=>{
console.log(err);
})
This question already has answers here:
How do I convert an existing callback API to promises?
(24 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm currently refactoring some code, and I'm running into a problem.
I am trying to return the value from inside an anonymous function. I played around with it a few different ways, and tried await-ing it.
Essentially I'm getting data about the request that's being made, not the data from the request.
Here are some different ways I've tried working with it -
const run = async (text) => {
...
const s = personalityInsights.profile(req, (err, data) => {
...
return data; // correct value
});
return s; // incorrect value
};
const run = async (text) => {
...
personalityInsights.profile(req, (err, data) => {
...
return data;
});
};
const run = async (text) => {
...
return personalityInsights.profile(req, (err, data) => {
...
return data;
});
};
I can give the full code, but I think this is more of a language specific problem I have, than a code specific one.
Thanks for your help,
Ollie
Edit: This question has been marked as a duplicate, which I understand - but the solutions in that duplicate simply aren't working, and they aren't things I haven't already tried...
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 5 years ago.
Although I found similar questions to mine, I couldn't solve the problem on my own.
In my '../models/user' model I want to find all users and put them into array, and return that array to the controller(where I will use the info).
Here is my code:
var mongoDatabase = require('../db');
var database = mongoDatabase.getDb();
function find() {
var test;
database.collection("customers").find().toArray( function(err, docs) {
if(err) throw err;
console.log(docs); //works fine
//I'd like to return docs array to the caller
test = docs;
});
console.log(test); //test is undefined
}
module.exports = {
find
};
I also noticed, that 'console.log(test)' goes before 'console.log(docs)'. I tried passing 'docs' argument as function parameter to 'find', but without result.
The best way is to use Promises. Do it like this.
function getUsers () {
return new Promise(function(resolve, reject) {
database.collection("customers").find().toArray( function(err, docs) {
if (err) {
// Reject the Promise with an error
return reject(err)
}
// Resolve (or fulfill) the promise with data
return resolve(docs)
})
})
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am relatively new to Javascript and I really don't understand what I am doing wrong here but the return value is not being set :
found = _dataDictionary.findOne(findByModelNameQuery, function(err, result) {
if (result) {
if (result.record) {
found = true
} else {
found = false
}
}
return found
});
As you are using callback functions (the function in the last parameter in findOne), to return results, I sugest to you to use a callback function.
To get the result, you may do something like:
function myFunction(myParams, callback){
_dataDictionary.findOne(myParams, function(err,result){
return callback(err,result);
});
}
Then you can call "myFunction" in other place like:
...
myFunction(params, function(err,result){
//do something with the result)
}
OBS1: if the params are an another function, the "ugly" way to do this is using nested callbacks, that usually are a "antipattern".
function myFunction(myParams, callback){
_dataDictionary.findOne(myParams, function(err,result1){
_anotherAsyncFunction(result1.params, function(err,result2){
//do something with result2 and callback it.
});
});
}
OBS2: You can avoid this antipattern using libraries such async "waterfall" method or bluebird Promise Library "then" methods.
It appears that _dataDictionary.findOne is an asynchronous function. So the value returned from the statement is not the same as the one assigned later inside the callback.
Refactoring your example will hopefully show you this:
_dataDictionary.findOne(findByModelNameQuery, function(err, result) {
if (result) {
if (result.record) {
found = true
} else {
found = false
}
}
// This statement returns to the `findOne` line executing this callback
// return found;
// Instead you can log here to see the value
console.log('FOUND', found);
});
UPDATE: based on your comments (and a few more assumptions) you could refactor to provide the value back to the calling function:
Model.observe('access', function(ctx, next, cb) {
var _dataDictionary = loopback.findModel('dataDictionary');
_dataDictionary.findOne(findByModelNameQuery, function(err, result) {
if (result) {
if (result.record) {
found = true;
} else {
found = false;
}
}
// Assuming cb is the method to return values if async
cb(found);
});
// Assuming this is for async behavior to notify to the `observe` caller that this is an async callback
next();
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a function that creates an object based on db data, and some web_based json.
function makeObject(dbdata){
var obj = {};
obj.id = dbdata.id;
obj.url = dbdata.url;
request(dbdata.url,function(err,res,body){
obj.inventory = JSON.parse(body).inventory;
});
return obj
}
This obviously doesn't fill in the inventory property (async, etc...) nor does it work with the return inside request. I know the answer is pretty basic, but I just can't see it. help,please!
You can either pass in a callback argument or return a promise. request has to return a promise or you have to promisify it in some way. The callback solution is easier to get going as it stands.
function makeObject(dbdata, cb) {
/* your codes */
request(args, function (err, res, body) {
obj.inventory = JSON.parse(body).inventory;
cb(err, obj);
});
}
Then you would use it like so
makeObject(dbdata, function (err, obj) {
// handle err
// do things with obj
});