functions in functions nodejs - node.js

I want to get the klout score using a screen name (twitter).
I did this. I know it doesn't work like that, but I don't know how it should work.
function get_klout(screenName){
klout.getKloutIdentity(screenName, function(error, klout_user) {
klout.getUserScore(klout_user.id, function(error, klout_response) {
return Math.round(klout_response.score);
});
});
}
I want my function to return this number Math.round(klout_response.score);

function get_klout(screenName) {
klout.getKloutIdentity(screenName, function(error, klout_user) {
klout.getUserScore(klout_user.id, function(error, klout_response) {
return Math.round(klout_response.score);
});
});
}
Your function is async, so you can't just assign what it returns to a variable because you will just assign undefined:
var result = get_klout('foo'); // undefined
what you can do is:
using async functions in node 8+
using Promises
using callbacks:
function get_klout(screenName, done) {
klout.getKloutIdentity(screenName, function(error, klout_user) {
klout.getUserScore(klout_user.id, function(error, klout_response) {
done(Math.round(klout_response.score));
});
});
}
get_klout('foo', function(response) {
console.log(response);
});
just a note:
In node is a common pattern implementing the error first callback and you should have a look on it because it's the traditional and more used way to handle errors:
http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/

Because this is an asynchronous function you cannot use return, in order to return result from asynchronous code pass to your function callback and return the result on the callback. you should handle errors in your callbacks.
function get_klout(screenName, callback){
klout.getKloutIdentity(screenName, function(error, klout_user) {
if (err){
callback(error);
return
}
klout.getUserScore(klout_user.id, function(error, klout_response) {
if (err){
callback(error);
return
}
callback(null, klout_response.score);
});
});
}
get_klout(screenName, function(err, res){
if (err){
console.log(err);
return
}
console.log(res);
});

Related

How to get to be return and print in outside function using node js

I tried one simple function in node js and pass data to one file on to another file.but its throwing undefined.how to solve it in node js
fun.js
function Get_Value()
{
client.get('products', function(err,results) {
return results
})
console.log(results)
}
I tried to print value in outside the function but its print undefined how to print result in out side function
async function Get_Value() {
let results = await new Promise(function(resolve) {
client.get("products", function(err, results) {
resolve(results);
});
});
console.log(results);
}
This is very easy using async/await features provided by ES7.
async function Get_Value()
{
const results = await new Promise((resolve, reject) => {
client.get('products', function(err,results) {
resolve(results);
})
});
console.log(results);
}
Define your Get_Value to take a callback function. You then pass a callback when you're invoking Get_Value:
function Get_Value(callback) {
client.get('products', function(err,results) {
if (err) return callback(err)
callback(null, results);
})
}
function mycallback(err, data) {
if (err) {
// handle error
console.error(err)
} else {
console.log(data);
}
}
Get_Value(mycallback)

Asynchronous function - node.js

I have a question about asynchronous function. Here my function "My_function":
function My_function (my_name, callback){
stmt = db.prepare ("SELECT number_table1 from my_table1 WHERE user=?");
stmt.bind(my_name);
stmt.get(function(error,row){
if(error){
throw err;
}
else{
if(row){
callback(number_table1);
}
else{
console.log("error");
}
}
});
}
Work fine but I have 2 tables and I need do other query and I need add two numbers so... in my function I need do too this query:
stmt = db.prepare ("SELECT number_table2 from my_table2 WHERE user=?");
and finally return back in my callback "number_table1 + number_table2".
Somebody know how to solve it? Thanks in advance.
Best regards!
In cases like your's I like to use the async module, because the code will be more legible. Example:
var async = require('async');
function My_function(my_name, callback) {
var stmt = db.prepare("SELECT number_table1 from my_table1 WHERE user=?");
stmt.bind(my_name);
stmt.get(function (error, row) {
if (error) {
callback(error, null);
} else {
if (row) {
callback(null, number_table1);
} else {
callback(new Error("row not found"), null);
}
}
});
}
//if you need the results in a specific order, you can use "series" instead of "parallel".
async.parallel(
//array of functions
[
function (callback) {
My_function('firstName', callback);
},
function (callback) {
My_function('secondName', callback);
}
],
//results when all functions ends
//the results array will equal [number_table1, number_table2], but the order can be different, because of the parallelism
function (err, results) {
if (err) {
//handle the err
} else {
//do something
}
}
);
Docs:
http://caolan.github.io/async/docs.html#parallel or
http://caolan.github.io/async/docs.html#series
You need to synchronize the functions so that you can be sure both their results are ready before calling back. You can do this using promises: https://www.promisejs.org/
Make two regular functions (no callbacks), one for each query (function1, function2)
Make both return a promise
Then you can do
function My_function(my_name) {
var value1;
function1(my_name)
.then(function(resultFromFunction1) {
value1 = resultFromFunction1;
return function2(my_name);
})
.then(function(resultFromFunction2) {
var result = value1 + resultFromFunction2;
return result;
});
}
}
Make sure to catch errors and handle different outcomes, what I presented is its simplest form.
Update
Here is an example of a function doing a query and returning a promise
function1 = function(user) {
return new Promise(function (resolve, reject) {
pool.getConnection(function (err, connection) {
if(err) {
reject ({status : false, message : "Error in connection database"});
} else {
connection.query('SELECT number_table1 from my_table1 WHERE user=?', [user], function(err, rows){
connection.release();
if(!err) {
resolve ({status: true, message: rows});
} else {
reject ({status: false, message: err});
}
});
}
});
});
}
Make the table names function parameters. Convert that function to use async/await or promise. Use Promise.all to run both queries.

NodeJs and Protractor return a value from the shared file

this.queryMailApi = function(mailUrl, callback) {
request.get({url: mailUrl}, function (err, httpResponse, body) {
if (err) {
return console.error('post failed:', err);
} else
callback(body);
});
};
this.myCallBack = function(data) {
var emailData = data;
console.log(emailData);
}
This is my function + callback to get the value. I want to return it to a function call similar to how you would do this.
var x = shared.queryMailApi(mailApiUrl, shared.myCallBack);
To be used later in code. I've read a ton of things about asynchronous Nodejs stuff which means I can't actually do this... but there has to be a way.
I didn't try this, but I think you should be able to do this in in this way with a promise.
this.queryMailApi = function(mailUrl) {
var deferred = protractor.promise.defer();
request.get({url: mailUrl}, function (err, httpResponse, body) {
if (err) {
deferred.reject(err);
return console.error('post failed:', err);
}
deferred.resolve(body);
});
return deferred.promise
};
this
.queryMailApi('example#mail.com')
.then(function(response) {
console.log(response);
});
If this doesn't work, you may take a look webdriver.WebDriver.wait. This may be useful.

node.js - dictionary changes when passed to callback

I am using the async.map function to call a neo4j database on each element of "arrayOne".
async.map(
arrayOne,
function(item, callback){
getClientsNb({id:item},function (err, res) {
if (err) {console.log(err); return callback(err);}
console.log(res.results[0].data); //1
callback(null,res.results[0].data);
});
},
function(err,res) {
if (err) return console.log(err);
console.log(res); //2
}
)
The first console.log displays what I want:
[ { row: [ 'DIE ZAUBERFLOETE-2013', 1355 ] } ]
But the second console.log in the final function does not display the same result:
[ { row: [Object] } ],
Where does it come from? I would like to have the same result in the second console.log.
NB: the getClientsNb function is the following:
function getClientsNb(param, callback) {
request.post({
uri: httpUrlForTransaction,
json: {statements: [{
statement: 'MATCH (n:Show {id:{id}})<-[:BUYS]-(m) RETURN n.name, count(distinct m)',
parameters: param}]}
},
function (err, res, body) {
if (err) {
console.log(err);
return callback(err)
} else {
return callback(null,body)
}
}).auth('neo4j', password, true);
}
[EDITED]
By changing the second console.log() call to output the data as JSON, you can display more details about what you are actually getting back: console.log("%j", res);. The result is probably in that Object.
Additional issue
This may or may not not solve the issue you are asking about, but you do have a logic error with respect to error handling.
async.map() requires that its callback be called once for every item in the array. But in your code, if the anonymous callback passed to getClientsNb() is passed an err value, it returns without ever calling callback.
This code fixes the above issue:
async.map(
arrayOne,
function(item, callback){
getClientsNb({id:item}, function (err, res) {
if (err) { console.log(err); return callback(err); }
console.log(res.results[0].data); //1
callback(null,res.results[0].data);
});
},
function(err,res) {
if (err) return console.log(err);
console.log(res); //2
}
)

How to implement Async with Mongoose method

I've got following code now:
exports.listByUser = function(req, res) {
Attack.find({user: req.user._id}, function(err, attacks) {
if(err)
return next(err);
for(var i in attacks) {
attacks[i].evaluateFight();
}
res.json(attacks);
});
};
the main problem is that attacks[i].evaluateFight() is called asynchronously, I want to transform it to make sure that [i-1] iteration is done ... and finally call res.json(attacks). I think, it can be done with async, but I don't know how :( Something like this should work, but how can I call attacks.method?
async.eachSeries(attacks, function (callback) {
//something??
callback();
}, function (err) {
if (err) { throw err; }
res.json(attacks);
});
You can leverage async whilst method call to implement the same. However, there is question I have about the callback of evaluateFight because if it is executed asynchronously then there has to be some callback associated with it which will notify if the previous call is succeeded.
The example code can be as follows assuming evaluateFight returns a callback when completed -
exports.listByUser = function(req, res) {
Attack.find({user: req.user._id}, function(err, attacks) {
if(err)
return next(err);
var attacksLength = attacks.length;
var count = 0;
async.whilst(function () {
return count < attacksLength;
},
function (callback) {
attacks[count].evaluateFight(function(err, result){
count++;
callback();
}); // assuming it returns a callback on success
},
function (err) {
// all the iterations have been successfully called
// return the response
res.json(attacks);
});
};

Resources