May be I am not asking it in right way. I am kind of new on Tizen.
Here is my code set for tizen.
respons = tizen.filesystem.resolve("documents", function(dir)
{
file = dir.resolve("myfile.txt");
if(file.isFile){ //if file is present then fetch the information.
var res_one = file.openStream("r",
function(fs) {
var my_json = JSON.parse(fs.read(file.fileSize));
fs.close();
res_two = my_json.json_value;
return res_two;
},
function(e) {
console.log("Error " + e.message);
return null;//if there is any error then return null
}, "UTF-8");
return res_one;
}
else{
return null; //if file is not present then return null
}
});
Basically I have a file present on my display(Installed Tizen OS) that contains a json:
json_value: "My Information"
I am trying to fetch the information to use that in my javascript code. I am able to fetch that information(Checked using console.log). But it is not being returned in res_one or in response.
In short form I want to access that json outside tizen.filesystem.resolve( ...
Thanks in advance.
I have done it. Basically this is asynchronous behaviour of javascript so I have done it using call back.
function to_fetch_the_value_and_chain_process(passed_function){
tizen.filesystem.resolve("documents", function(dir){
file = dir.resolve("myfile.txt");
if(file.isFile){ //if file is present then fetch the information.
var res_one = file.openStream("r",
function(fs) {
var my_json = JSON.parse(fs.read(file.fileSize));
fs.close();
res_two = my_json.json_value;
passed_function(res_two);
},
function(e) {
console.log("Error " + e.message);
passed_function(null);;//if there is any error then return null
}, "UTF-8");
return res_one;
}
else{
passed_function(null); //if file is not present then return null
}
});
}
funtion passed_function(retrieve_res_two){
alert(retrieve_res_two );
//use retrieve_res_two and chain the next code here.....
}
to_fetch_the_value_and_chain_process(passed_function);
Related
In the following sample of code I send a "request" and I am trying to get a response but that returns "undefined" value.
This is my code so far
$scope.SameNameFunction = function() {
var payload = { itemname: $scope.EventDetails.Name};
portalRepository.namecall(payload).then(function (payload) {
console.log(payload.valuesreturned);
alert("Detected: " + payload.valuesreturned + " events having the same name");
});
};
Code from the http.post
namecall: function (payload) {
return $http.post("/Api/PortalData/NameNumberResult", payload);
},
Code from the .cs controller:
public ActionResult NameNumberResult(ItemEventNameDTO payload)
{
var valuetosend = payload.itemname;
var acf = new AcFunctions();
var newstorevalue = SqlHelper.ExecuteDataset(acf.AcConn(), "sp_selectbyname", valuetosend);
payload.valuesreturned = newstorevalue.Tables[0].Rows.Count;
return payload.GetSuccess();
}
Putting a breakpoint I am getting the appropriate value from the stored procedure, either in .cs and .js files. But while trying to print the message in screen, value do not appear and "Detected undefined events having the same name" is showing instead.
Any help is welcome!
As you per your code, you are returning promise
namecall: function (payload) {
return $http.post(url, payload);
}
You need to use the callback method of $http.post()
portalRepository.namecall(payload).then(function(data){
alert("Detected: " + payload.valuesreturned + " events having the same name");
});
I am trying to upload a picture as well as some other data, which is captured from a form, to my Parse database. A lot of this code is copied from the Parse Javascript guide. The name, price and description details upload fine, but the picture never uploads. What I get on my log is:
adding item...
Item sucessfully added!
Item sucessfully uploaded!
In that order... I'm not sure why this would happen especially since i'm using the whole promise paradigm. Why would the item be added before the image is uploaded? And why isn't this code working?
function addItem()
{
console.log('adding item...');
var Item = Parse.Object.extend("FoodItem");
var newItem = new Item();
newItem.set("createdBy", Parse.User.current());
newItem.set("name",$('#itemName').val());
newItem.set("price",parseInt($('#itemPrice').val()));
newItem.set("description",$('#itemDescription').val());
//Upload pic to parse cloud
var fileUploadControl = $("#itemImage")[0];
if (fileUploadControl.files.length > 0)
{
var file = fileUploadControl.files[0];
var name = "photo.jpg";
var parseImage = new Parse.File(name, file);
}
parseImage.save().then
(
function()
{
newItem.set(name,parseImage);
console.log("Image sucessfully uploaded!");
return;
}
).then
(
newItem.save().then
(
function()
{
console.log("Item sucessfully added!")
},
function(error)
{
// there was some error.
alert("Saving item failed with error code " + error.message);
}
)
);
return false;
}
.then() takes functions as arguments. In your second .then() you want to pass a function to be called when the promise is resolved. Instead you are actually calling the function and passing the results to then.. so that function gets called before the first promise resolves. Also, you should return a promise from your first .then(). I think the following should work:
parseImage.save().then(function() {
newItem.set(name,parseImage);
console.log("Image sucessfully uploaded!");
return newItem.save();
})
.then(function() {
console.log("Item sucessfully added!")
},
function(error) {
// there was some error.
alert("Saving item failed with error code " + error.message);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to learn Node.js
I am having trouble creating my own call back on a function. It seems like such a simple thing but I don't quite understand how to do it.
The function is passed an address (example: "1234 will ln, co") which uses google's geolocate json api to return the full address, latitude and longitude in an array.
Here is my code:
//require secure http module
var https = require("https");
//My google API key
var googleApiKey = "my_private_api_key";
//error function
function printError(error) {
console.error(error.message);
}
function locate(address) {
//accept an address as an argument to geolocate
//replace spaces in the address string with + charectors to make string browser compatiable
address = address.split(' ').join('+');
//var geolocate is the url to get our json object from google's geolocate api
var geolocate = "https://maps.googleapis.com/maps/api/geocode/json?key=";
geolocate += googleApiKey + "&address=" + address;
var reqeust = https.get(geolocate, function (response){
//create empty variable to store response stream
var responsestream = "";
response.on('data', function (chunk){
responsestream += chunk;
}); //end response on data
response.on('end', function (){
if (response.statusCode === 200){
try {
var location = JSON.parse(responsestream);
var fullLocation = {
"address" : location.results[0].formatted_address,
"cord" : location.results[0].geometry.location.lat + "," + location.results[0].geometry.location.lng
};
return fullLocation;
} catch(error) {
printError(error);
}
} else {
printError({ message: "There was an error with Google's Geolocate. Please contact system administrator"});
}
}); //end response on end
}); //end https get request
} //end locate function
So when I try to execute my function
var testing = locate("7678 old spec rd");
console.dir(testing);
The console logs undefined because its not waiting for the return from locate (or at least I am guessing this is the problem).
How do i create a call back so when the locate function returns my array, it runs the console.dir on the array it returned.
Thanks! I hope my question makes sense, im self taught so my tech jargon is horrible.
You need to pass in the callback function to your method - so the callback might look something like this
function logResult(fullLocation){
console.log(fullLocation)
}
You would pass this in to your locate method along with the input:
// note: no parentheses, you're passing a reference to the method itself,
// not executing the method
locate("1234 will ln, co",logResult)
You can also do this inline - much like the response object you're already dealing with:
locate("1234 will ln, co",function(fullLocation){
// do something useful here
})
Now for the bit inside your method, instead of trying to return the result you just call the callback with the result:
function locate(address, callback) {
......
response.on('end', function (){
if (response.statusCode === 200){
try {
var location = JSON.parse(responsestream);
var fullLocation = {
"address" : location.results[0].formatted_address,
"cord" : location.results[0].geometry.location.lat + "," + location.results[0].geometry.location.lng
};
callback(fullLocation); // <-- here!!!
} catch(error) {
printError(error);
}
} else {
printError({ message: "There was an error with Google's Geolocate. Please contact system administrator"});
}
}); //end response on end
.....
}
So, I'm defining a cloud function that's supposed to make a call to the foursquare api and generate a list of restaurants (each restaurant is a ParseObject) from the returned JSON. I successfully do this, but I run into problems when trying to save these objects to my database and send them back to my phone by calling response.success(). The large code block below saves the list to my database, but if I try
Parse.Object.saveAll(restaurants)
response.success(restaurants)
I end the function before all of the restaurants are saved. I tried using this line instead
Parse.Object.saveAll(restaurants).then(response.success(restaurants))
, but only half of the restaurants get saved before I get the error "Failed with: Uncaught Tried to save an object with a pointer to a new, unsaved object." I also get this error if I call response.success(restaurants) without attempting to save the list. I read that this is a bug in parse preventing someone from printing or passing unsaved ParseObjects. Any ideas? I also tried using .then on the http request, but I get the same issues or a new error: "com.parse.ParseException: i/o failure: java.net.SocketTimeoutException: Read timed out. "
Parse.Cloud.define("callFourSquare", function(request, response) {
//The Parse GeoPoint with current location for search
var geo = request.params.location;
var geoJson = geo.toJSON();
var url = "https://api.foursquare.com/v2/venues/explore?ll=" + geoJson.latitude + ","
+ geoJson.longitude + "§ion=food&sortByDistance=1&limit=50&venuePhotos=1&categoryId=4d4b7105d754a06374d81259&client_id= C043AJBWKIPBAXOHLPA0T40SG5L0GGMQRWQCCIKTRRVLFPTH"
+ "&client_secret=Y1GZZRHXEW1I3SQL3LTHQFNIZRDCTRG12FVIQI5QGUX0VIZP&v=20140715";
console.log(url);
//Call to FourSquare api, which returns list of restaurants and their details
Parse.Cloud.httpRequest({
method: "GET",
url: url,
success: function (httpResponse) {
var restaurants = [];
var json = httpResponse.data;
var venues = json.response.groups[0].items;
console.log(venues.length)
for(i = 0; i < venues.length; i++) {
venue = venues[i].venue;
var RestaurantObject = Parse.Object.extend("Restaurant");
var rest = new RestaurantObject();
try {
rest.set("geoLocation",
new Parse.GeoPoint({latitude: venue.location.lat,
longitude: venue.location.lng}));
} catch(err) {}
try {
rest.set("address", venue.location.address + " " + venue.location.formattedAddress[1]);
} catch(err) {}
try {
rest.set("phoneNumber", venue.contact.formattedPhone);
} catch(err) {}
try {
rest.set("website", venue.url);
} catch(err) {}
rest.set("name", venue.name);
rest.set("lowerName", venue.name.toLowerCase());
try {
rest.set("priceLevel", venue.price.tier);
} catch(err) {}
try {
rest.set("rating", venue.rating/2);
} catch(err) {}
try {
rest.set("storeId", venue.id);
} catch(err) {}
try {
rest.set("icon", venue.photos.groups[0].items[0].prefix + "original"
+ venue.photos.groups[0].items[0].suffix)
} catch(err) {}
restaurants.push(rest);
}
Parse.Object.saveAll(restaurants);
},
error: function (httpResponse) {
response.error("Request failed with response code:" + httpResponse.status + " Message: "
+ httpResponse.text);
}
});
});
I believe your issue is that you aren't returning the Promise from Parse.Object.saveAll(restaurants) when your httpRequest() is complete. Try returning that saveAll() promise and see if it completes.
I'm doing server side validation for the files uploaded. Not every file that makes it to the server is stored. How can I display/trigger the error on the file(s) that were not successfully stored on the server. I've tried adding a server Validation function but can't figure out how to do it... Please help
this.on("successmultiple", function (file, successResponse) {
uploadResult = eval(successResponse);
toastr.options.positionClass = "toast-bottom-right";
var ErrorMessage = "";
for (var i = 0; i < uploadResult.ResultList.length; i++) {
var result = uploadResult.ResultList[i];
if (result.IsSuccessful === "True") {
toastr.success(result.Message);
if (hdnFileIDList !== "")
hdnFileIDList = hdnFileIDList + "|" + result.ID;
else
hdnFileIDList = result.ID
}
else {
//-- trigger dropzone error
toastr.warning(result.Message);
//this.ValidationError(file, result.Message);
file.accepted = false;
file.status = Dropzone.ERROR;
dropzone.serverError(file, result.Message);
//dropzone.emit("errormultiple", file, result.Message);
}
}
$("#<%=hdnSharedFileObjNewFileIDList.clientID%>").val(hdnFileIDList);
});
Solved my problem by adding the following code to Dropzone.js then calling it from my "successmultiple" event when I see and error in my returned JSON from the server.
Dropzone.prototype.serverError = function (file, message) {
file.accepted = false;
file.status = Dropzone.ERROR;
return this._errorProcessing(file, message);
};
To anyone else that's landed here after searching for a solution to this problem: there's a pretty simple and elegant way to deal with this without getting into the guts of Dropzone. If your server side validation fails, return a status code of 400 (bad request) and include your error message as a jsonResponse.
Then you can handle the response with something like the following code in your dropzone's init configuration (assuming you are sending your error message as "ValidationMessage"):
this.on("error", function (file, jsonResponse) {
var errorMessage = "Could not upload document: ";
if (jsonResponse["ValidationMessage"] != null) {
errorMessage += jsonResponse["ValidationMessage"];
} else {
errorMessage += "unknown error";
}
alert(errorMessage);
});
The file will have a big red X on it just like a regular Dropzone failed upload.
This solution is for single uploads rather than multiple but the same idea should work for multiple.