我对解析 javascript 代码非常陌生,并且在异步任务方面遇到问题。 所以我认为我必须使用 Promise。
因此,我的代码的目标是获取创建体育赛事的用户,并在收到后向他们发送通知。 由于异步任务,发送通知的代码是在使用 Parse query.find 方法获取用户 ID 之前到达的。
这是我的代码:
//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) {
}
);
});
当我运行此作业时,我收到以下消息:
return Parse.Promise.as("Hello");
} has no method 'then'
at main.js:99:6
非常感谢任何可以帮助我的人。
塞巴斯蒂安
最佳答案
要将 promise 串联起来,您可以编写如下:
...
//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(...)
还可以看看 Promise in Series文档中的部分。
关于javascript - 使用 Promise 和 Parse Javascript 代码来避免异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27174298/