I've tried a few variations of this snippet. I keep getting the same undefined error when trying to print a json object to the console. Thanks in advance.
var userTweets = client.get('statuses/user_timeline', function(error, tweets, response){
if(error) throw error;
return tweets
});
console.log(userTweets)
client.get is asynchronous
This code is working, then you have to manage your code to wait for asynchronous response.
client.get('statuses/user_timeline', function(error, tweets, response){
if(error) throw error;
console.log(tweets)
});
If you have some code after client.get, you should do that
before :
var userTweets = client.get(..., function() {});
// do some code
console.log(userTweets);
after :
client.get(....., function(error, tweets) {
...
otherCode(tweets);
});
function otherCode(userTweets) {
// do some code
console.log(userTweets);
}
I suggest you to read this answer : https://stackoverflow.com/a/11233849/5384802 to understand asynchronous code.
Related
I am using this async module for asynchronously requesting
web content with the help of another module request, as this is an asynchronous call.
Using async.each method, for requesting data from each link,
the result is also successfully returned by the scrap() function (which I have wrote to scrap returned html data
and return it as array of fuel prices by state).
Now, the problem is that when I try to return prices back to async.each() using cb(null, prices), it shows console.log(prices) as undefined
but logging inside the _check_fuel_prices(), works fine. It seems the callback works with only one argument
(or error only callback, as show as an example in the async.each link above). What if I want to it return prices (I can change it with error like cb(prices), but I also want to log error).
router.get('/someRoute', (req, res, next) => {
const fuels = ['diesel', 'petrol'];
async.each(fuels, _check_fuel_prices, (err, prices) => {
if (!err) {
res.statusCode = 200;
console.log(prices);
return res.json(prices);
}
res.statusCode = 400;
return res.json(err);
});
function _check_fuel_prices(fuel, cb) {
let prices = '';
const url_string = 'http://some.url/';
request(`${url_string}-${fuel}-price/`, (error, response, html) => {
if (error) {
cb(error, null);
return;
}
if (response.statusCode === 404) {
console.log(response.statusCode);
cb('UNABLE TO FIND PAGE', null);
return;
}
prices = scrap(html, fuel);
console.log(prices);
cb(null, prices);
return;
});
}
});
As #generalhenry points out, I was able to get the prices by using async.map which returns error first callback instead of error only apart from that async.series can be used here by slightly changing the code.
I want to update a field in the 'NotesDB' that indicates the number of comments on a specific Note. Parse Cloudcode should do this automatically after saving a comment.
In practice it sometimes does and it sometimes doesn't (even with the same user, on the same note). The comment itself is always saved properly.
Is there any way i can improve this code..?
Parse.Cloud.afterSave("CommentsDB", function(request) {
var OriginalNote = request.object.get("OriginalPostId");
var query = new Parse.Query("NoteDB");
query.get(OriginalNote, {
success: function(post) {
post.increment("NumberOfComments");
post.save();
},
error: function(error) {
console.log("An error occured :(");
}
});
As you code stands, it is not possible to see if the post.save() call is failing or not (and if it is, why), maybe try chaining your promises :
query.get(OriginalNote,{useMasterKey:true}).then (function (post) {
post.increment("NumberOfComments");
return post.save(null,{useMasterKey:true});
}).then (function (savedPost) {
console.log('post incremented ok to ' + savedPost.get('NumberOfComments'));
},function (err) {
//this function will catch any error in the promise chain : query.get() or post.save()
console.error('An error occured : ' + err.message);
});
So I'm unable to find any examples and the example used on the npm package README throws me an error.
So I'm using https://github.com/Datahero/node-eventbrite
I require it in app.js. I create the token variable and place my token in there.
I add this piece of snippet in
try {
var api = eventbriteAPI({
token: eventbrite_token,
version : 'v3'
});
} catch (error) {
console.log(error.message); // the options are missing, this function throws an error.
}
So on the README file it says the next line of code should be something like (replacing the user_id: with my user id).
api.owned_events({ user_id: 30 }, function (error, data) {
if (error)
console.log(error.message);
else
console.log(JSON.stringify(data)); // Do something with your data!
});
I get the error TypeError: api.owned_events is not a function
Basically I'm trying to get a list of events based on the location from the Eventbrite API via node. But I'm unable to even query from node and get what I want back. Has anyone any resources or can offer help?
Thank you!
I think there is an error on the README file, api should be declared outside the try/catch block:
var api;
try {
api = eventbriteAPI({
token: eventbrite_token,
version : 'v3'
});
} catch (error) {
console.log(error.message);
}
api.owned_events({ user_id: 30 }, function (error, data) {
if (error)
console.log(error.message);
else
console.log(JSON.stringify(data)); // Do something with your data!
});
Maybe I've been staring at my code too long or maybe I'm using too many callbacks elsewhere or something, but I can't figure out the logistics of this one. I know the value contained in rows is correct from using util.inspect(rows) on it inside that callback function. I just don't know how to bring it back up to the surface, so to speak. dbHandler() is called from other functions that pass the params and a result is expected in return.
Any insight would be tremendously helpful.
Using node.js with Express and mysql packages if that makes a difference.
function dbHandler(req, res, params) {
pool_user.getConnection(function (err, connection) {
if (err) {
connection.release();
res.json({
"code" : 100,
"status" : "Error in connection database"
});
return;
}
connection.query(params.query_string, function (err, rows) {
connection.release();
if(!err) {
res.json(rows); // <<--- I want to get ahold of the value of `rows`
//console.log(util.inspect(rows));
}
});
connection.on('error', function(err) {
res.json({
"code" : 100,
"status" : "Error in connection database"
});
return;
});
});
}
Trying to return the result of an async function is an anti-pattern and will never work.
Instead, restructure the calling code.
Not Like This - the anonymous callback does not return to the caller
new_data = api_request_data(auth, request,
function(error, data){
return data;
});
store(new_data);
update_screen(new_data);
Better
api_request_data(auth, request,
function(error, data){
store(data);
update_screen(data);
});
Best
api_request_data(auth, request,
function(error, data){
if (error){
console.log(error);
return;
}
store(data);
update_screen(data);
});
In your code, the data pipeline looks ok.
connection.query(params.query_string, function (err, rows) {
connection.release();
if(!err) {
res.json(rows); // <<--- I want to get ahold of the value of `rows`
//console.log(util.inspect(rows));
}
});
The code res.json(rows); in a node.js application will queue a JSON string containing the data in rows for writing to the current web connection referenced in res.
Your question suggests that the issue is that this line does not return data to the caller of dbHandler(), but no trained node.js developer would expect that to happen. The code looks correct for delivering the data in rows to an over-the-web client of the node.js application.
I'm trying to run Parse cloud code for the first time from an AngularJS app. I keep getting the Parse.Error 'unauthorized' in my console.log. I've initialized Parse in my application and JS keys. Where am I going wrong?
Angular Code Format:
$scope.runSomething = function () {
Parse.Cloud.run('nameFunction', req.body, {
success: function (result){
},
error: function (error){
console.log(error);
}
})
I derive the req.body for the Parse.Cloud.run from prestanding info in the $scope.runSomething function.
My truncated main.js:
Parse.Cloud.define('nameFunction', function(request, response){
Parse.Cloud.useMasterKey();
//Do Stuff})
I'm sure I'm missing something small but I have no idea what.
It sounds like you're close. Cloud functions (including before/after functions) must call success or error on the response object to properly complete, so...
Parse.Cloud.define('nameFunction', function(request, response){
Parse.Cloud.useMasterKey();
var someParam = request.params.someParam;
doSomePromiseReturningThing(someParam).then(function(result) {
response.success(result);
}, function (error) {
response.error(error);
});
});