Parse "Unexpected identifier in main.js" in my Cloud Code - javascript

I am trying to deploy my newly written cloud code function to Parse but I keep getting the error "Unexpected identifier" at line 110, I can't seem to figure out how there is an error here, any help?
Parse.Cloud.define("backgroundJob", function(request, response) {
Parse.Cloud.useMasterKey();
var moments = require("cloud/moments.js");
var now = moments.moment();
var groupObject = Parse.Object.extend("Group");
var query = new Parse.Query(groupObject);
var eventObject = Parse.Object.extend("Event");
query.find().then(function(groups) {
var promise = Parse.Promise.as();
_.each(group, function(result) {
promise = promise.then(function() {
var count = 0;
var events = _.map(result.get("Events"), function(eventArray) {
if (now == eventArray[count].get('date') {
var curEvent = eventArray[count];
eventArray[count].destory();
var relationc = result.get("created");
var createdq = relationc.query();
var relationj = result.get("created");
var joinedq = relationj.query();
var partOnee = curEvent.get("name");
var outString = partOnee.concat(" is now");
Parse.Push.send({
where: createdq,
data: {
alert: outString
}
}).then(function() {
response.success();
}, function(error) {
response.error(error);
});
Parse.Push.send({
where: joinedq,
data: {
alert: outString
}
}).then(function() {
response.success();
}, function(error) {
response.error(error);
});
}
count = count+1;
});
});
});
}).then(function() {
response.success()
}, function(error) {
response.error(error);
});
});
Line 110 is var curEvent = eventArray[count];

You missed ) in this line if (now == eventArray[count].get('date'), see:
var events = _.map(result.get("Events"), function(eventArray) {
if (now == eventArray[count].get('date') {
Fix:
var events = _.map(result.get("Events"), function(eventArray) {
if (now == eventArray[count].get('date')) {
Note, when interpreters/compilers (in most programming languages) say there is a problem on a line, usually the problem can be in any row before.

Related

jQuery post not working on safari but works on chrome

i've been facing a safari issue where a JQuery post method works on chrome but it does not on safari unless i set JQuery post async to false with this piece of code
$.ajaxSetup({ async: false });
also page redirect does not work on safari, but it works on chrome
window.location.href = data.url;
any idea why i'm getting this behavior on safari and how to fixe it.
here is the code that i'm using
$('#submit').click( function () { //post
if ($('form').validate().checkForm() === false) {
alert('Form is invalid.');
return;
}
var tool = $("#Tool").val();
var email = $("#Email").val();
var message = $("#Message").val();
var attachement0 = $("#Attachement0").val();
var attachement1 = $("#Attachement1").val();
var attachement2 = $("#Attachement2").val();
var attachement3 = $("#Attachement3").val();
var attachement4 = $("#Attachement4").val();
var dataToPost = {};
dataToPost.Tool = tool;
dataToPost.Email = email;
dataToPost.Message = message;
dataToPost.Attachement0 = attachement0;
dataToPost.Attachement1 = attachement1;
dataToPost.Attachement2 = attachement2;
dataToPost.Attachement3 = attachement3;
dataToPost.Attachement4 = attachement4;
// $.ajaxSetup({ async: false });
$.post("#Url.Action("BugReport_Send_JQuery","BugReport")", { model: dataToPost }).done(function (data) {
if (data.status == 1) {
alert(data.message);
window.location.href = data.url;
}
else if (data.status == 0) alert(data.error);
});
});
server side post method
[HttpPost]
public async Task<IActionResult> BugReport_Send_JQuery(User_BugReportViewModel model)
{
if (ModelState.IsValid)
{
var bugReport = new BugReportModel()
{
Tool = model.Tool,
Email = model.Email,
Message = model.Message,
Attachement0 = model.Attachement0,
Attachement1 = model.Attachement1,
Attachement2 = model.Attachement2,
Attachement3 = model.Attachement3,
Attachement4 = model.Attachement4,
Resolved = false,
CreationDate = DateTime.Now,
ResolutionDate = new DateTime(),
};
try
{
await appDBContext.BugReportsTB.AddAsync(bugReport);
await appDBContext.SaveChangesAsync();
}
catch (Exception e)
{
return Json(new { status = 0, error = e.Message });
}
return Json(
new
{
status = 1,
message = "A ticket has been created, Thank you for your coperations!",
url = Url.Action("TicketCreate", "Email", new { email = bugReport.Email }),
});
}
return Json(new { status = 0, error = "something went wrong!" });
}

Convert this LINQ code back to a Loop (or Why is this object sometimes null)

I have an Upload Button in an app that uploads a deliveries object, but sometimes the deliveries object is null when it gets to the web service.
Full code is below, but it is this bit that I am having trouble unpicking. I believe this is LINQ code, so can anyone help me convert this back into a loop so that I can begin to try and understand why the deliveries object might be null?
var deliveries = Enumerable.From(results).Select(function (r) {
r.transactionDate = r.transactionDate.format("YYYY-MM-DD HH:mm:ss");
return r;
}).ToArray();
Full code:
me.uploadClicked = function () {
playClicked();
coreViewModel.busyMessage("Processing delivery data...");
deliveryRepository.GetTodaysDeliveries(function (results) {
var deliveries = Enumerable.From(results).Select(function (r) {
r.transactionDate = r.transactionDate.format("YYYY-MM-DD HH:mm:ss");
return r;
}).ToArray();
window.setTimeout(function () {
coreViewModel.busyMessage("Uploading delivery data...");
var objUploadDeliveries = Object.create({
objStore: Object.create({
storeTypeID: coreViewModel.store.storeTypeID(),
storeID: coreViewModel.store.id()
}),
objDeliveries: deliveries
});
var comm = new URLHelper();
var xhr = $.ajax({
url: comm.hosturl() + "UploadDelivery",
type: 'POST',
beforeSend: function(xh) { xh.setRequestHeader("token", coreViewModel.token); },
data: objUploadDeliveries,
dataType: 'json',
success: function (result) {
if (!result) {
playError();
return;
}
playUploadComplete();
},
error: function (x, e) {
playError();
errorHandler(x, e);
},
timeout: 60000
});
}, 20000);
});
}
The GetTodaysDeliveries function is as follows:
GetTodaysDeliveries: function (callback) {
deliverysDatabase.GetDeliveries(function (results) {
$.each(results, function (index, result) {
result.transactionDate = moment(result.transactionDate).utc();
});
var todaysResults = Enumerable.From(results).Where(function (r) {
return moment().isSame(r.transactionDate, 'day');
}).ToArray();
return callback(todaysResults);
});
}
and the deliverydatabase.GetDeliveries function inside that is as follows:
GetDeliveries: function (callback) {
var me = this;
db.transaction(
function (context) {
context.executeSql("SELECT barcode, titleName, delivered, expected, isNews, supplier, supplierId, transactionDate FROM delivery ORDER BY titlename", [], function (context, result) {
if (result.rows.length > 0) {
var results = [];
for (var i = 0; i < result.rows.length; i++) {
results.push(result.rows.item(i));
}
return callback(results);
} else {
return callback([]);
}
}, me.ErrorHandler);
}
, me.ErrorHandler);
}
Your code snippet takes the array from results, formats the date, and then returns an array. So deliverables is the same as results but with date formatted. If delivarables is null, then results must be empty or null. You can check this by inserting a
console.log("test");
into the loop
This is the unlinqd code snippet
var deliveries = [];
results.forEach(function(item)
{
var item.transactionDate = item.transactionDate.format("YYYY-MM-DD HH:mm:ss");
deliveries.push(item);
};
I hope this clears it up.

Function is not returning data back to my array

im having a problem with my function Mrequest,the problem is that data like id and year are not add to de array. I know is a problem with the function but i just cant solve it.
any idea of what could i change so my array result get the ID and the YEAR
function getContent() {
var result = [];
async.series([
getDb,
getInfos
]);
function getDb(done) {
//posta
var query = "SELECT title , launch_year FROM content WHERE content_genre_id=1 && content_type_id!=2 LIMIT 2;"
mysqlConnection.query(query, function(err, data) {
result = data;
async.each(result, getPelicula, done);
});
}
function Mrequest(pagina, callback){
request({
url: pagina,
method: "GET",
json: true,
}, callback);
}
function getPelicula(pelicula, donePelicula) {
var peli = pelicula.title;
var pagina = "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false"
setTimeout(function() {
Mrequest(pagina, function(error, res, body) {
if (error) {
console.log("error", error);
} else {
var control = body.results.length;
if (control > 0) {
var year_base = pelicula.launch_year;
var id = body.results[0].id;
var year = body.results[0].release_date;
var d = new Date(year);
var year_solo = d.getFullYear();
console.log(pelicula);
console.log("id",id);
console.log("year",year);
console.log("year",year_solo);
if (year_base == year_solo) {
pelicula.id = id;
pelicula.year_pagina = year_solo;
} else {
pelicula.id = -1;
pelicula.year_pagina = null;
}
}
}
});
}, result.indexOf(pelicula) * 3000);
donePelicula();
}
getContent();
}
it doesn't look like you are making the request because getContent is being called from within itself

Parse cloud code - modifying all PFUsers

I'm trying to create a cloud Job that takes the users full name or username and saves it in lower case in another column. here's what I have so far:
Parse.Cloud.job('normaliseUsername',function(request, status) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.find({
success: function(items){
for (var i=0;i<items.length;i++) {
var user = items[i];
console.log(user);
var changed = user["nameChanged"];
if (changed === true) {
var username = user.username;
user.set("lowerCaseName",username.toLowerCase());
} else {
var realName = user["firstName"] + " " + user["lastName"];
user.set("lowerCaseName",realName.toLowerCase());
}
user.save();
}
}
});
});
This results in a new column, lowerCaseName, full of undefined.
how do I access properties of a PFUser in this instance? I have tried using user.get(''); but it says Cannot call method 'get' of undefined
Do it this way :
Parse.Cloud.job("normaliseUsername", function(request, status) {
Parse.Cloud.useMasterKey();
var count_user = 0;
var query = new Parse.Query(Parse.User);
query.descending('updatedAt');
query.Exist('nameChanged');
query.limit(1000);
return query.find().then(function(users) {
return Parse.Promise.when(users.map(function(user) {
count_user+= 1;
if (user.get("nameChanged")) {
user.set("canonical_firstname", user.get("username").toLowerCase());
} else {
var realName = user.get("firstname") + ' ' + user.get("lastname");
user.set("lowerCaseName", realName.toLowerCase());
}
return user.save();
}));
}).then(function() {
status.success("normaliseUsername with " + count_user + " user(s) updated.");
}, function(error) {
status.error("Uh oh, something went wrong.");
});
});
Your loop with for, will never works, you need to use Promise. More information here : http://blog.parse.com/learn/engineering/whats-so-great-about-javascript-promises/
The way the above script works, you will work with Promise in Parallel, not in Series : https://parse.com/docs/js/guide#promises

WinJS Virtualized Data Source + nested asynchronous requests

Hi i'm relatively new to JavaScript and i'm working on a winjs app project where i want to use the Bing image search data source example in my project to virtualize the datasource of a listview.
My problem is understanding how the asynchronous functions work together and how to implement an async xhr request within the existing one.
Currently i'm using a synchronous request but i would like to change that into a asynchronous one.
This is my data adapter:
(function () {
var xxxDataAdapter = WinJS.Class.define(
function (devkey, query, delay) {
this._minPageSize = 2;
this._maxPageSize = 5;
this._maxCount = 50;
this._devkey = devkey;
this._query = query;
this._delay = 0;
},
{
getCount: function () {
var that = this;
var requestStr = 'http://xxx/' + that._query;
return WinJS.xhr({ url: requestStr, type: "GET", /*user: "foo", password: that._devkey,*/ }).then(
function (request) {
var obj = JSON.parse(request.responseText);
if (typeof obj.error === "undefined") {
var count = obj.length;
if (count === 0) { console.log("The search returned 0 results.", "sample", "error"); }
return count;
} else {
console.log("Error fetching results from API", "sample", "error");
return 0;
}
},
function (request) {
if (request && request.name === "Canceled") {
return WinJS.Promise.wrapError(request);
} else {
if (request.status === 401) {
console.log(request.statusText, "sample", "error");
} else {
console.log("Error fetching data from the service. " + request.responseText, "sample", "error");
}
return 0;
}
});
},
itemsFromIndex: function (requestIndex, countBefore, countAfter)
{
var that = this;
if (requestIndex >= that._maxCount) {
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist));
}
var fetchSize, fetchIndex;
if (countBefore > countAfter) {
//Limit the overlap
countAfter = Math.min(countAfter, 0);
//Bound the request size based on the minimum and maximum sizes
var fetchBefore = Math.max(Math.min(countBefore, that._maxPageSize - (countAfter + 1)), that._minPageSize - (countAfter + 1));
fetchSize = fetchBefore + countAfter + 1;
fetchIndex = requestIndex - fetchBefore;
} else {
countBefore = Math.min(countBefore, 10);
var fetchAfter = Math.max(Math.min(countAfter, that._maxPageSize - (countBefore + 1)), that._minPageSize - (countBefore + 1));
fetchSize = countBefore + fetchAfter + 1;
fetchIndex = requestIndex - countBefore;
}
var requestStr = 'http://xxx/' + that._query;
return WinJS.xhr({ url: requestStr, type: "GET", /*user: "foo", password: that._devkey,*/ }).then(
function (request)
{
var results = [], count;
var obj = JSON.parse(request.responseText);
if (typeof obj.error === "undefined")
{
var items = obj;
for (var i = 0, itemsLength = items.length; i < itemsLength; i++)
{
var dataItem = items[i];
var req = new XMLHttpRequest();
// false = synchronous
req.open("get", "http://xxxxx/" + dataItem.id, false);
req.send();
var jobj = JSON.parse(req.response);
if (typeof jobj.error === "undefined")
{
results.push({
key: (fetchIndex + i).toString(),
data: {
title: jobj.name.normal,
date: Date.jsonFormat(dataItem.calculatedAt, "Do, MMM HH:mm Z"),
result: "",
status: "",
}
});
}
}
return {
items: results, // The array of items
offset: requestIndex - fetchIndex, // The offset into the array for the requested item
};
} else {
console.log(request.statusText, "sample", "error");
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist));
}
},
function (request)
{
if (request.status === 401) {
console.log(request.statusText, "sample", "error");
} else {
console.log("Error fetching data from the service. " + request.responseText, "sample", "error");
}
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.noResponse));
}
);
}
});
WinJS.Namespace.define("xxx", {
datasource: WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function (devkey, query, delay) {
this._baseDataSourceConstructor(new xxxDataAdapter(devkey, query, delay));
})
});
})();
And this is the synchronous request i would like to change to an asynchronous one:
var req = new XMLHttpRequest();
// false = synchronous
req.open("get", "http://xxxxx/" + dataItem.id, false);
req.send();
you can use then function to chain promises. In your scenario, then function need to simple have a if statement.
return WinJS.xhr(params).then(function (req)
{
if (..)
return WinJS.xhr(params2);
else
return; // then function ensures wrapping your sync result in a completed promise
}, function onerror(e)
{
// todo - error handling code e.g. showing a message box based on your app requirement
});
This is what i came up with. Map the json objects received asynchronously and make another asynchronous call for each object to get additional data. Then the nested async calls are joined and returned when all are finished.
return WinJS.xhr({ url: 'http://xxx=' + that._query }).then(function (request) {
var results = [];
var obj = JSON.parse(request.responseText);
var xhrs = obj.map(function (dataItem, index) {
return WinJS.xhr({ url: 'http://xxxx' + dataItem.attrx }).then(
function completed(nestedRequest) {
var xxJobj = JSON.parse(nestedRequest.responseText);
var dataObj = {};
dataObj.title = xxJobj.name;
dataObj.date = Date.jsonFormat(dataItem.attrtrxx, "Do, MMM HH:mm Z");
dataObj.result = "open";
dataObj.status = "foo";
if (dataItem.xx.hasOwnProperty("attrx5")) {
dataObj.opponent = dataItem.attrx4;
} else {
dataObj.opponent = dataItem.attrx3;
}
dataObj.page_title = "xXx";
dataObj.match_id = dataItem.id;
dataObj.type = "largeListIconTextItem";
dataObj.bg_image = "http://xxx/" + xxJobj.attrx2 + "-portrait.jpg";
results.push({
key: (fetchIndex + index).toString(),
data: dataObj
});
},
function (err) {
console.log(err.status);
console.log(err.responseText);
}
);
});
return WinJS.Promise.join(xhrs).then(
function (promises) {
return {
items: results, // The array of items
offset: requestIndex - fetchIndex, // The offset into the array for the requested item
};
},
function (err) {
console.log(JSON.stringify(err));
}
);
});

Categories