Parse.com: cannot create more than 9 objects using cloud job - javascript

I have Cloud Job code like this:
Parse.Cloud.job("createMySpecialObjects", function(request, status) {
var MySpecialObject = Parse.Object.extend("MySpecialObject");
var count = 20 // 20 is greater than 9!
for (var i = 0; i < count; i++) {
var myObject = new MySpecialObject();
myObject.save();
}
status.success("Objects created successfully.");
});
And I have only 9 created objects as result.
I suppose it is connected with 30 API calls per second. But maybe somebody else knows better?

The code snippet below shows how to save multiple objects by using Parse.Object.saveAll.
Parse.Cloud.job("createMySpecialObjects", function(request, status) {
var MySpecialObject = Parse.Object.extend("MySpecialObject");
var count = 20 // 20 is greater than 9!
var toSaves = [];
for (var i = 0; i < count; i++) {
var myObject = new MySpecialObject();
toSaves.push(myObject);
}
Parse.Object.saveAll(toSaves, {
success: function(saveList) {
status.success("Objects created successfully.");
},
error: function(error) {
status.error("Unable to save objects.")
}
}
});

Related

LearnYouNode: Juggling Async without BL/Async/After

I was following this tutorial when a wild step 9 appears.
This problem is the same as the previous problem (HTTP COLLECT) in that you need to use http.get(). However, this time you will be provided with three URLs as the first three command-line arguments.
You must collect the complete content provided to you by each of the URLs and print it to the console (stdout). You don't need to print out the length, just the data as a String; one line per URL. The catch is that you must print them out in the same order as the URLs are provided to you as command-line arguments.
My code was (It doesn't work fine just when he pleases):
http = require("http");
var url = [process.argv[2], process.argv[3], process.argv[4]];
var responses = [];
var completed_responses = 0;
for(var i in url){
http.get(url[i], function(response){
var content = "";
//if(completed_responses == url.length){
response.setEncoding("utf-8");
response.on("data", function(data){
content += data;
})
response.on("error", console.error);
response.on("end", function(end){
console.log(content);
});
})
}
And the answer was:
var http = require("http");
var bl = require("bl");
var results = [];
var count = 0;
function printResults(){
for(var i = 0; i < 3; i++)
console.log(results[i]);
}
function httpGet(index){
http.get(process.argv[2 + index], function(response){
response.pipe(bl(function(err, data){
if (err)
return console.error(err);
results[index] = data.toString();
count++;
if(count == 3)
printResults()
}))
})
}
for(var i = 0; i < 3; i++)
httpGet(i);
What is the right answer WITHOUT BL/AFTER/ETC?
Thanks to all!
I've done that tutorial myself when I was first learning node and I remember that step of the tutorial. The solution was fairly underwhelming. Anyway, for your answer:
NodeJs Asynchronous programming - Coordinating parallel calls
You can check the code in the question and make the fixes I suggested in my answer. That should solve it without BL/Async/Whatever else that tutorial mentions.
Here is my code for the Juggling Async challenge without using any third-party libraries.
var http = require("http");
var urls = [process.argv[2], process.argv[3], process.argv[4]];
var urlResults = new Array("", "", "");
var allDoneCount = 0;
urls.forEach(function (_url) {
http.get(_url, function (resp) {
resp.on("data", function (data) {
if (_url === urls[0]) {
urlResults[0] += data.toString();
} else if (_url === urls[1]) {
urlResults[1] += data.toString();
} else {
urlResults[2] += data.toString();
}
})
resp.on("end", function () {
allDoneCount++;
if (allDoneCount === 3) {
console.log(urlResults[0]);
console.log(urlResults[1]);
console.log(urlResults[2]);
}
})
resp.on("error", function (err) {
console.log(err);
})
}).on("error", function (err) {
console.log(err);
})
})
This is how you can do it without any external modules(except http ;P).
const http = require('http'); //http module
let results = ["", "", ""]; //this will store the data from http.get()
let counter = 0; //to keep a counter for no of httpget's done
//it will iterate when counter is 3 i.e. the 'end' for all
function print() {
for (let i = 0; i < 3; i++) {
console.log(results[i]);
}
}
//accept index(for process.argv) as parameter
function httpGetter(i) {
//http.get method on the url first encountered, 2+i because 2 values are reserved
http.get(process.argv[2 + i], (res) => {
//for converting (res)ponse to string/alternatively toString() method can be used
res.setEncoding('utf8');
//event data on the url, callback with recived chunk as parameter
res.on('data', function(chunk) {
//appending the recived chunk to that element of results corresponding to 'i' of httpGetter function
results[i] += chunk;
});
//event end, when no more data is read
//runs every time for each value of 'i' that is for each url
res.on('end', function() {
//to keep count
counter++;
//when 3 that is when data from all inputs receved
if (counter === 3) {
//print function simply iterating over results array
print();
}
});
})
}
//inputs are recieved from here
for (let i = 0; i < 3; i++) {
//i can be index for results
httpGetter(i);
}

Parse Cloud Code - Notifcation not working and objects not deleting

I have a Parse Cloud Code function that will act as my background job. Right now I am in my debugging stage. The function does not throw an error and it is not doing what it is supposed to do. The function entitled "backgroundJob" is supposed to go through all the "Group" objects that have been created. Each "Group" object has an Array of "Event" objects, and all you have to know about the "Event" object is it has a date property called "date".
The function should go through all the events for each group object and if the event's date is the same as the current time the function should send a notification to all "Users" who are apart of that group and then delete that event. Right now the function is not deleting the event if it is the same time as the current time and is not notifying members of the group.
My function is below.
Parse.Cloud.define("backgroundJob", function(request, response) {
Parse.Cloud.useMasterKey();
var moments = require("cloud/moment.js");
moments().format();
var _ = require('cloud/underscore.js');
// Get the actual time, for use in non testing
// var now = moments();
// For testing edit time in ()
var now = moments("2015-23-11 19:30", "YYYY-MM-DD HH:mm");
var out = now;
console.log(out);
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();
var groupArray = groups;
for (var i = 0; i < groupArray.length; i++) {
promise = promise.then(function() {
var count = 0;
var eventArray = groupArray[i].get("Events");
for (count = 0; count < eventArray.length; count++) {
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);
});
var e = eventArray[count];
var destroyp = Parse.Promise.as();
destroyp = promise.then(function() {
return e.destroy();
}, function(error) {
response.error(error);
});
}
}
});
}
}).then(function() {
response.success()
}, function(error) {
response.error(error);
});
});
Thank you.
For reference in the code there are two separate relations to users a "created" and a "joined", this is why in the code I have a created query and a reaction query.
You have a typo in your code. Maybe this is not the cause of the issue, but anyways, check it.
eventArray[count].destory();
Seems silly, but, who knows...

nested javascript queries in parse

I have the code below. Basically I have 3 nested parse queries. One is getting a number of "followers" and for each follower I am getting a number of "ideas" and for each idea I would like to get that idea creator's name (a user in the user table).
The first two nested queries work but then when i try to get the name of the user (the creator of the idea), that last nested query DOES NOT execute in order. That query is skipped, and then it is executed later in the code. Why is this happening please?
var iMax = 20;
var jMax = 10;
var IdeaList = new Array();
var IdeaListCounter = 0;
var myuser = Parse.User.current();
var Followers = new Parse.Query("Followers");
Followers.equalTo("Source_User",{__type: "Pointer",className: "_User",objectId: myuser.id});
Followers.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var Ideas = new Parse.Query("Ideas");
Ideas.equalTo("objectId_User", {__type: "Pointer",className: "_User",objectId: object.get('Destination_User').id});
Ideas.find({
success: function(results2) {
for (i=0;i<iMax;i++) {
IdeaList[i]=new Array();
for (j=0;j<jMax;j++) {
IdeaList[i][j]=0;
}
}
for (var j = 0; j < results2.length; j++) {
var object2 = results2[j];
var ideausername2 = "";
IdeaListCounter++;
var ideausername = new Parse.Query("User");
ideausername.equalTo("objectId",object2.get('objectId_User').id);
ideausername.first({
success: function(ideausernameresult) {
ideausername2 = ideausernameresult.get("name");
}
});
IdeaList[IdeaListCounter,0] = object2.get('objectId_User').id + " " + ideausername2; //sourceuser
IdeaList[IdeaListCounter,1] = object2.get('IdeaText'); //text
IdeaList[IdeaListCounter,2] = object2.get('IdeaImage'); //image
IdeaList[IdeaListCounter,3] = object2.get('IdeaLikes'); //likes
IdeaList[IdeaListCounter,4] = object2.get('IdeaReport'); //reports
Your nested query is asynchronous.
Check out the answer at the following for guidance:
Nested queries using javascript in cloud code (Parse.com)

Javascript array results returning undefined

I have been working on a simple math game and am having problems getting the overall answer results to return after the end of the game.
Here is what my return function looks like
function pShowResults() {
var pNumResults = document.getElementById("results");
for (var i = 0; i <= 10; i++) {
pNumStore.push(pNumGuess[i]);
var pNumTable = document.createElement("div");
pNumTable.innerHTML = (pNumGuess[i]);
pNumResults.appendChild(pNumTable);
}
}
Here is the full script
Pretty much need debugging help. I new to this so I'm guessing there is a ton that's off, but as long as I can get the results fed back I should be fine.
You are not passing the value of x in many placess
$(document).ready(function () {
//declare arrays and variables for use below
var pNum1 = [];
var pNum2 = [];
var pNumAns = [];
var pNumGuess = [];
var pNumStore = [];
var pNumCarry = 0;
var pNumTrack = 0;
var pNumMessageRight = ['Awesome Job!', 'Correct!', 'Great Job!'];
var pNumMessageWrong = ['Oh No! That Was Wrong!', 'Incorrect!', 'That\'s Wrong'];
$(".Play").click(function () {
$("#popup").attr("class", "on");
pNumTrack = 0;
pNumGen(pNumTrack);
});
$(".pNumSubmit").click(function () {
pNumCalc(pNumTrack-1);
});
$(".pNumNext").click(function () {
pNumGen(pNumTrack);
});
function pNumGen(x) {
pNum1[x] = (Math.round(Math.random() * 51));
pNum2[x] = (Math.round(Math.random() * 51));
pNumAns[x] = pNum1[x] + pNum2[x];
$(".pNum1").html(pNum1[x]);
$(".pNum2").html(pNum2[x]);
$(".pNumGuess").val("");
$(".pNum1").html(pNumTrack[x]);
if (pNumTrack == 2) {
$(".pNumNext").html("");
$(".pNumSubmit").html("Close");
pShowResults();
}
pNumTrack++;
}
function pNumCalc(x) {
pNumGuess[x] = $(".pNumGuess").val();
if (pNumGuess[x] == pNumAns[x]) {
$(".message").html(pNumMessageRight[Math.floor(Math.random() * pNumMessageRight.length)]);
$(".pNumNext").html("Next Question >")
} else {
$(".message").html(pNumMessageWrong[Math.floor(Math.random() * pNumMessageWrong.length)]);
$(".pNumNext").html("Maybe The Next Question >")
}
}
function pShowResults() {
var pNumResults = document.getElementById("results");
for (var i = 0; i < pNumGuess.length; i++) {
pNumStore.push(pNumGuess[i]);
var pNumTable = document.createElement("div");
pNumTable.innerHTML = (pNumGuess[i]);
pNumResults.appendChild(pNumTable);
}
}
});
Demo: Fiddle
There is a function called pNumCalc in your code which you have set to take in an argument, but you never pass one in. You use the argument to store the results in the pNumGuess array, but since the argument is never passed in, the guesses are never stored, and you end up with undefined as the answers the user gave.
Updated fiddle: http://jsfiddle.net/dwdX9/2/. Not sure how close this is to what you actually want though, but hopefully it gets you on the right track.
Because StackOverflow wants code to to be included when JSFiddle is...:
pNumCalc(pNumTrack)
You forget to define array before use it.
function pShowResults() {
var pNumStore = new Array();
var pNumResults = document.getElementById("results");
for (var i = 0; i <= 10; i++) {
pNumStore.push(pNumGuess[i]);
var pNumTable = document.createElement("div");
pNumTable.innerHTML = (pNumGuess[i]);
pNumResults.appendChild(pNumTable);
}
}
I must suggest you should use jquery instead.
After visiting your Fiddle seems like there are many problems with the code. and also your question is unclear.
for e.g.
$(".pNumSubmit").click(function () {
//why x value not passed?
pNumCalc();
});
function pNumCalc(x) {
pNumGuess[x] = $(".pNumGuess").val();
if (pNumGuess[x] == pNumAns[x]) {
$(".message").html(pNumMessageRight[Math.floor(Math.random() * pNumMessageRight.length)]);
$(".pNumNext").html("Next Question >")
} else {
$(".message").html(pNumMessageWrong[Math.floor(Math.random() * pNumMessageWrong.length)]);
$(".pNumNext").html("Maybe The Next Question >")
}
}
Please clear which array is returning undefined so that others can help you.

Issues accessing an object's array values - returns null or 0s

The function below should return an array of objects with this structure:
TopicFrequency = {
name: "Chemistry", //This is dependent on topic
data: [1,2,3,4,5,6,7,8,9,10,11,12] //This would be real data
};
so when I do this:
myData = this.getChartData("line");
it should return two objects:
{name : "Chemistry", data : [1,2,3,4,51,12,0,0, 2,1,41, 31]}
{name : "Math", data : [0,0,41,4,51,12,0,0, 2,1,41, 90]}
so when I do console.log(myData); it's perfect, returns exactly this.
However when I do console.log(myData[0].data) it returns all 0s, not the values. I'm not sure what this issues is known as, and my question is simple what is this problem known as?
Here is the full function. Somethings were hardcoded and other variables (notable server and queryContent) removed. Those parts worked fine, it is only when manipulated/retreiving the returned array's values that I run into problems. Note this is async. so not sure if that is also part of the problem.
getChartData: function (chartType) {
var TopicsFrequencyArray = new Array();
timePairs = this.newIntervalSet("Month");
topicList = new Array("Chemistry", "Math");//Hard coded for now
var queryCopy = {
//sensitive information
};
for (i = 0; i < topicList.length; i++) {
var TopicFrequency = {
name: null,
data: this.newFilledArray(12, 0)
};
j = 0;
TopicFrequency.name = topicList[i];
while (j < timePairs.length) {
queryCopy.filter = TopicFrequency.name;
//additional queryCopy parameter changes made here
var request = esri.request({ url: server, content: queryCopy, handleAs: "json", load: sucess, error: fail });
j = j + 1;
function sucess(response, io) {
var topicCountData = 0;
query = esri.urlToObject(io.url);
var dateString = query.query.fromDate.replace("%", " ");
dateString = dateString.replace(/-/g, "/");
dateString = dateString.split(".");
date = new Date(dateString[0]);
dojo.forEach(response.features, function (feature) {
if (feature.properties.count > 0) {
topicCountData = feature.properties.count;
}
TopicFrequency.data[date.getMonth()] = topicCountData;
});
}
function fail(error) {
j = j + 1;
alert("There was an unspecified error with this request");
console.log(error);
}
}
TopicsFrequencyArray.push(TopicFrequency);
}
},

Categories