Nodejs - issue with a response - google-places-api

// I am unable to get the data from https.get into a variable
// We need to assign the httpd return to the global.city variable.
global.city ;
https.get(url, function(response) {
var body ='';
response.setEncoding("utf8");
response.on('data', function(chunk) {
body += chunk;
//console.log(body);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
}).on('response',function(f){
console.log("lets dance");
}).on('end', function() {
var places = JSON.parse(body);
locations = places.results;
return locations ;
global.city = locations ; // I get the data here.
console.log(global.city);
/* the data is seen here */
});;
console.log(global.city); // No response outside the function.

The data is retrieved asynchronously, so when you print the result (console.log(global.city);) the data is not available yet.
This is how you do it:
global.city ;
https.get(url, function(response) {
var body ='';
response.setEncoding("utf8");
response.on('data', function(chunk) {
body += chunk;
//console.log(body);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
}).on('response',function(f){
console.log("lets dance");
}).on('end', function() {
var places = JSON.parse(body);
locations = places.results;
return locations ;
global.city = locations ; // I get the data here.
console.log(global.city);
/* the data is seen here */
goOn();
});;
function goOn() {
// continue your code here
console.log(global.city); // global.city has value now
}
Hope this helps, but I suggest you look up how Javascript works.

Related

Parallel asynchronous Ajax calls from the client

I have 20 data packet in the client and I am pushing one by one to the server via Ajax post. Each call take approximately one minute to yield the response. Is there any way to make few of these requests run parallel.
I have used Jquery promise. However, still the request waiting for the prior one to get completed.
var dataPackets=[{"Data1"},{"Data2"},{"Data3"},{"Data4"},{"Data5"},
{"Data6"},{"Data7"},{"Data8"},{"Data9"},{"Data10"},
{"Data11"},{"Data12"},{"Data13"},{"Data14"},{"Data15"},{"Data16"},
{"Data17"},{"Data18"},{"Data19"},{"Data20"}];
$(dataPackets).each(function(indx, request) {
var req = JSON.stringify(request);
setTimeout({
$.Ajax({
url: "sample/sampleaction",
data: req,
success: function(data) {
UpdateSuccessResponse(data);
}
});
}, 500);
});
The when...done construct in jQuery runs ops in parallel..
$.when(request1(), request2(), request3(),...)
.done(function(data1, data2, data3) {});
Here's an example:
http://flummox-engineering.blogspot.com/2015/12/making-your-jquery-ajax-calls-parallel.html
$.when.apply($, functionArray) allows you to place an array of functions that can be run in parallel. This function array can be dynamically created. In fact, I'm doing this to export a web page to PDF based on items checked in a radio button list.
Here I create an empty array, var functionArray = []; then based on selected items I push a function on to the array f = createPDF(checkedItems[i].value)
$(document).ready(function () {
});
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function exportPDFCollection() {
var f = null;
var x = 0;
var checkedItems = $("input:checked");
var count = checkedItems.length;
var reportList = $(checkedItems).map(
function () {
return $(this).next("label").text();
})
.get().join(",");
var functionArray = [];
var pdf = null;
for (var i = 0; i < count; i++) {
f = createPDF(checkedItems[i].value)
.done(function () {
pdf = checkedItems[x++].value;
alert('PDF => ' + pdf + ' created.');
})
.fail(function (jqxhr, errorText, errorThrown) {
alert('ajax call failed');
});
functionArray.push(f);
}
$.when.apply($, functionArray)
.done(function () {
$.get("http://yourserver/ExportPage.aspx",{reports: reportList})
.done(function () {
alert('PDF merge complete.');
})
.fail(function (jqxhr, errorText, errorThrown) {
alert('PDF merge failed. Please try again.');
});
return true;
});
}
function createPDF(webPage) {
return $.get(webPage);
}

Execute multiple http request - Parse Cloud Code

i have an array of stores, where the address and some other things are stored.
Now I want to iterate through this array and geocode the lat / lng coords and save them to the database.
With the code below I get double or triple entries of the same store. Do I miss something with the scope here?
Thanks!
var promises = [];
data.forEach(function (element, index)
{
var addressString = element.plz + " " + element.stadt + "," + element.adresse;
var url = encodeURI("https://maps.googleapis.com/maps/api/geocode/json?address=" +
addressString);
var promise = Parse.Cloud.httpRequest({
method: "GET",
url:url
}).then(function (http) //SUCCESS
{
var geocodedObject = new Parse.Object("GeocodedStores");
geocodedObject.set("storeID", element.id);
geocodedObject.set("Latitude", http.data.results[0].geometry.location.lat);
geocodedObject.set("Longitude", http.data.results[0].geometry.location.lng);
return geocodedObject.save(null, {
useMasterKey: true
});
},
function (http, error)
{
response.error(error);
});
promises.push(promise);
});
return Parse.Promise.when(promises);
Finally found a working solution. It looked like it was a problem with the scope. I put the code in a seperate function and added this returned promise to an array.
var fn = function(element, geocodedObject)
{
var addressString = element.plz + " " + element.stadt + "," + element.adresse;
var url = encodeURI("https://maps.googleapis.com/maps/api/geocode/json?address=" +
addressString);
Parse.Cloud.httpRequest({
method: "GET",
url: url
}).then(function(http)
{
geocodedObject.set("storeID", element.id);
geocodedObject.set("Latitude", http.data.results[0].geometry.location.lat);
geocodedObject.set("Longitude", http.data.results[0].geometry.location.lng);
geocodedObject.set("address", addressString);
return geocodedObject.save(null, {
useMasterKey: true
});
});
}
var promises = [];
for (var k = 0;k<data.length;k++)
{
var geocodedObject = new Parse.Object("GeocodedStores");
promises.push(fn(data[k], geocodedObject));
}
Parse.Promise.when(promises).then(function () {
response.success("DONE");
});

ionic how to log http response in xcode

I am trying to upload an image to cloudinary using ionic cordova plugin. I can successfully post my image to cloudinary, but the response i received in xcode shows [object Object]. I would like to get the details of the response.
I tried printing the result using different ways such as iterating the keys of object, and nothing is been printed. is there a way for xcode to print out ionic console.log response? My code is as follow:
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, $cordovaCamera, $cordovaGeolocation, $cordovaFileTransfer, $q, $base64, $translate) {
//$scope.$inject = ['$cordovaCamera','$cordovaGeolocation','$cordovaFileTransfer'];
$scope.imageURI = '';
$scope.log=function(){
console.log('hello~~~');
};
$scope.takePicture = function() {
console.log('taking pictures ....');
var uploadOptions = {
params : { 'upload_preset': "MY_PRESET"}
};
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG,
};
$cordovaCamera.getPicture(options).then(function(imageData) {
$scope.imageURI = imageData;
var ft = new FileTransfer();
function win (){
console.log('upload successful');
}
function fail(){
console.log('upload fail');
}
return $cordovaFileTransfer.upload("https://api.cloudinary.com/v1_1/MY_DOMAIN/image/upload", $scope.imageURI, uploadOptions);
})
.then(function(result){
console.log('result is~~~~~~ ', result);
console.log('print the result object '); // this shows nothing
var test1=JSON.parse(decodeURIComponent(result.response);
var test2=JSON.parse(decodeURIComponent(result);
console.log('test1 is ', test1); // didn't even print!!
console.log('test2 is ', test2); // didn't even print!!
for(var property in result[0]) {
console.log(property + "=" + obj[property]); // nothing here
}
for(var property in result[1]) {
console.log(property + "=" + obj[property]);// nothing here
}
for(var property in result) {
console.log(property + "=" + obj[property]);// nothing here
}
var url = result.secure_url || '';
var urlSmall;
if(result && result.eager[0]) { // this is not working
urlSmall = result.eager[0].secure_url || '';
console.log('url ~~~~~~~~ is ', urlSmall);
chat.sendMessage(roomId,'', 'default', urlSmall, function(result){
console.log('url is ', urlSmall);
console.log('message image url successfully updated to firebase');
})
}
// Do something with the results here.
$cordovaCamera.cleanup();
}, function(err){
// Do something with the error here
console.log('something is erroring')
$cordovaCamera.cleanup();
});
};
})

Got promise not working

I'm trying to use promise to get in promise2
But if I have an object Widgets with several elements in it...
Why can't I have been able to get my console.log's output
Parse.Cloud.define("extract", function(request, response) {
var user = request.params.user;
var promise = Parse.Promise.as();
[...]
}).then(function() {
return query.find().then(function(results) {
_.each(results, function(result) {
[...]
Widget.objectId = result.id;
Widgets[timestamp] = Widget;
});
return promise;
}).then(function(results) {
for (var key in Widgets) {
var Widget = Widgets[key];
var widget_data = Widgets[key].widget_data;
var promise2 = Parse.Promise.as();
promise2 = promise2.then(function() {
return Parse.Cloud.run('extractWidgetData', {
'widget_data': widget_data,
}).then(function(newresult) {
Widgets[key].data = newresult.data;
console.log('--------WHY NOT HERE ALL TIME ?--------');
});
});
return promise2;
}
}).then(function() {
response.success(Widgets);
},
function(error) {
response.error("Error: " + error.code + " " + error.message);
});
});
});
I'm becoming crazy to run this damn Code
EDIT : I finally followed Roamer's advices to implement something but I'm not sure if it's the good way to work with Promise in series...
Parse.Cloud.define("extract", function(request, response) {
var user = request.params.user;
var Widgets = {};
...
... .then(function() {
return query.find().then(function(results) {
return Parse.Promise.when(results.map(function(result) {
var Widget = ...;//some transform of `result`
Widget.id = ...;//some transform of `result`
var timestamp = createdAtDate.getTime();
...
return Parse.Cloud.run('extractData', {
'widget_data': Widget.widget_data,
}).then(function(newresult) {
Widget.stat = newresult.stats;
return Widget;//<<<<<<< important! This ensures that results.map() returns an array of promises, each of which delivers a Widget objects.
});
}));
}).then(function() {
var promisedWidget = Array.prototype.slice.apply(arguments);
return Parse.Promise.when(promisedWidget.map(function(Widget) {
return Parse.Cloud.run('getWineStats', {
'id': Widget.data.id
}).then(function(stat) {
Widget.stat = stat;
return Widget;
});
}));
}).then(function() {
var promisedWidget = Array.prototype.slice.apply(arguments);
_.each(promisedWidget, function(Widget) {
var createdAtObject = Widget.createdAt;
var strDate = createdAtObject.toString();
var createdAtDate = new Date(strDate);
timestamp = createdAtDate.getTime();
Widgets[timestamp] = Widget;
});
return Widgets;
}).then(function(Widgets) {
response.success(Widgets);
},
function(error) {
response.error("Error: " + error.code + " " + error.message);
});
});
});
First, I echo Bergi's comment on indentation/matching parenthesis.
But ignoring that for a moment, at the heart of the code you have return query.find().then(...).then(...).then(...) but the flow from the first .then() to the second is incorrect. Besides which, only two .then()s are necessary as the code in the first then is synchronous, so can be merged with the second.
Delete the two lines above for (var key in Widgets) { then at least Widgets will be available to be processed further.
Going slightly further, you should be able to do all the required processing of results in a single loop. There seems to be little pont in building Widgets with _.each(...) then looping through the resulting object with for (var key in Widgets) {...}.
In the single loop, you probably want a Parse.Promise.when(results.map(...)) pattern, each turn of the map returning a promise of a Widget. This way, you are passing the required data down the promise chain rather than building a Widgets object in an outer scope.
Do all this and you will end up with something like this :
Parse.Cloud.define("extract", function(request, response) {
var user = request.params.user;
...
... .then(function() {
return query.find().then(function(results) {
return Parse.Promise.when(results.map(function(result) {
var Widget = ...;//some transform of `result`
...
return Parse.Cloud.run('extractWidgetData', {
'widget_data': Widget.widget_data,
}).then(function(newresult) {
Widget.data = newresult.data;
return Widget;//<<<<<<< important! This ensures that results.map() returns an array of promises, each of which delivers a Widget objects.
});
}));
}).then(function() {
//Here, compose the required Widgets array from this function's arguments
var Widgets = Array.prototype.slice.apply(arguments);//Yay, we got Widgets
response.success(Widgets);
}, function(error) {
response.error("Error: " + error.code + " " + error.message);
});
});
});

How do I emit to an eventListener from inside a nested function in Node.js (javascript scoping issue)

I am writing code below that parses a sites API one at a time, than tells an event queue it is ready for the next object to parse. I am having issues since I am still new to javascript scoping, and would like to emit from SiteParser or call the emitForNext function. I cannot seem to bring emitForNext into scope in the error callback.
function SiteParser(){
this.emitForNext = function (message) {
this.emit("next", message);
};
this.pullJSON = function (path, processJSON) { //processJSON is a callback function
var options = {
host: 'www.site.com',
port: 80,
path: path
}
//console.log("... processing "+path);
//pulls the entire json request via chunks
http.get(options, function (res) {
var resJSON = ''; //stores the comment JSON stream given in the res
res.on('data', function (chunk) {
resJSON+=chunk;
});
res.on('end', function () {
var obJSON = (JSON.parse(resJSON));
if (obJSON.hasOwnProperty("error")){
console.log(obJSON);
console.log('... ', path, ' does not exist');
//
//NEED A NEXT EVENT EMMITER HERE NEED TO FIGURE OUT SCOPE
//
//
} else {
processJSON(obJSON); //call the callback function
}
}) ;
}).on('error', function (e) {
emitForNext("got error: " + e.message);
});
};
}
JavaScript has function scoping, if you declare a variable with the var keyword, it will be local to the current function. When you access a variable, it will look to the scope chain which consist of the current function, it's parent function, …. Try:
function one() {
var foo = 'foo';
function two() {
console.log(foo) // undefined. I'll explain this
var foo = 'bar';
console.log(foo) // bar
}
two()
console.log(foo) // foo
}
one()
Most of the time we define variables at the beginning of functions, because a variable defined in function's body get hoisted. Basically, it means that it's available in the whole function, even before it's defined but in this case it's value is undefined.
For example if a variable is not defined we normally get a ReferenceError, but in the snippet below, both console.log() just print undefined.
function foo() {
console.log(bar);
if (0) {
var bar = 'bar';
}
console.log(bar);
}
So, a common practice is that, when you write long functions, you map this to self.
function SiteParser() {
var self = this;
// ...
.error('error', function(err) {
self.emitForNext("got " + err.message);
})
}
You should not write all your methods in the constructor, it's only usefull sometimes when we want privacy, but in this case you'd better use prototypes.
Putting this together, I would write:
var SiteParser = function() {};
SiteParser.prototype.emitForNext = function(message) {
this.emit("next", message);
};
SiteParser.prototype.pullJSON = function(path, processJSON) {
var self = this,
options = {
host: 'www.site.com',
port: 80,
path: path
};
http.get(options, function(res) {
// ...
}).on('error', function (e) {
self.emitForNext("got error: " + e.message);
});
};
To be able to access emitForNext, you need to call self.emitForNext, where self points to your instance of SiteParser.
Like so:
function SiteParser(){
this.emitForNext = function (message) {
this.emit("next", message);
};
this.pullJSON = function (path, processJSON) { //processJSON is a callback function
var options = {
host: 'www.site.com',
port: 80,
path: path
};
var self = this;
//console.log("... processing "+path);
//pulls the entire json request via chunks
http.get(options, function (res) {
var resJSON = ''; //stores the comment JSON stream given in the res
res.on('data', function (chunk) {
resJSON+=chunk;
});
res.on('end', function () {
var obJSON = (JSON.parse(resJSON));
if (obJSON.hasOwnProperty("error")){
console.log(obJSON);
console.log('... ', path, ' does not exist');
self.emitForNext(path + ' does not exist');
} else {
self.emitForNext('Successfully parsed the response');
processJSON(obJSON); //call the callback function
}
}) ;
}).on('error', function (e) {
self.emitForNext("got error: " + e.message);
});
};
}
However, it looks like you'd rather manage what you'll do next (like parsing the next object) in you callback, ie. in the body of processJSON.
You need to store link to 'this'' object in SiteParser local scope.
function SiteParser () {
var that = this; // store link to 'this' in local scope
this.emitForNext = function (message) {
this.emit("next", message);
};
this.pullJSON = function (path, processJSON) { //processJSON is a callback function
var options = {
host: 'www.site.com',
port: 80,
path: path
}
//console.log("... processing "+path);
//pulls the entire json request via chunks
http.get(options, function (res) {
var resJSON = ''; //stores the comment JSON stream given in the res
res.on('data', function (chunk) {
resJSON+=chunk;
});
res.on('end', function () {
var obJSON = (JSON.parse(resJSON));
if (obJSON.hasOwnProperty("error")){
console.log(obJSON);
console.log('... ', path, ' does not exist');
that.emitForNext();
} else {
processJSON(obJSON); //call the callback function
}
}) ;
}).on('error', function (e) {
that.emitForNext("got error: " + e.message);
});
};
}

Resources