Reputation: 35
I'm very new with Parse javascript code and i have a problem with asynchronous tasks. So i think that i have to use Promise.
So the goal of my code is to get users that created a sport event and to send them a notification after i get them. Because of asynchronous tasks, the code to send the notifications is reached before getting the users id with a Parse query.find method.
Here is my code:
//Background job whos goal is to send a push to the creator and the participants of
// a sport event
Parse.Cloud.job("sendPushOneHourBefore", function(request, response) {
var query = new Parse.Query("SportEvent");
var now = new Date();
now.setHours(now.getHours()+1);
query.greaterThan("date", now);
now.setMinutes(now.getMinutes()+30);
query.lessThan("date", now);
query.include("_User");
var userIds = [];
//Request to find all the sport events within an hour and a half
return query.find().then(function(sportevents) {
//getting the ids of the sportevent user's
for (var i = 0; i < sportevents.length; ++i) {
var userRelation = sportevents[i].relation("user");
userRelation.query().find().then(function(users){
{ for (var j in users)
{
console.log(users[j].id);
userIds[i] = users[j].id;
console.log("userIds[i]"+userIds[i]);
console.log("i:"+i);
console.log("userIds[0]"+userIds[0]);
console.log("userIds[1]"+userIds[1]);
}
}
}
);
// );
}
return Parse.Promise.as("Hello");
}.then(function(hello){
console.error("Error finding sport events " + error.code + ": " + error.message);
console.log("userIds[1] dans find-"+userIds[1]+"-");
var queryPush = new Parse.Query(Parse.Installation);
queryPush.containedIn('userId', userIds);
Parse.Push.send({
where: queryPush,
data: {
alert: "Votre evenement sportif va commencer bientot! Verifiez l'heure sur Whatteam!"
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
return Parse.Promise.as("Hello");
}),function(error) {
}
);
});
When i run this job, i have this message:
return Parse.Promise.as("Hello");
} has no method 'then'
at main.js:99:6
Thanks a lot to anyone who can help me.
Sebastien
Upvotes: 0
Views: 1188
Reputation: 813
To chain the promises in series, you could write as following:
...
//Request to find all the sport events within an hour and a half
return query.find().then(function(sportevents) {
var promise = Parse.Proimse.as();
//getting the ids of the sportevent user's
for (var i = 0; i < sportevents.length; ++i) {
var relationQuery = sportevents[i].relation("user").query();
promise = promise.then(function(){
return relationQuery.find().then(function(users) {
for (var j in users) {
console.log(users[j].id);
userIds[i] = users[j].id;
console.log("userIds[i]"+userIds[i]);
console.log("i:"+i);
console.log("userIds[0]"+userIds[0]);
console.log("userIds[1]"+userIds[1]);
}
return Parse.Promise.as('Hello')
});
});
}
return promise
}).then(...)
And also take a look at Promise in Series section in docs.
Upvotes: 1