我正在尝试使用parse.com服务从云代码(后台作业)实施高级推送定位。我已将该日添加为Installation对象中的字段。
如果我只有一个条件,即day等于1,则使用以下代码段
,这样就可以了var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("day",1);
Parse.Push.send({
where: pushQuery,
data: {
"content-available" : "1",
alert : "Message day 1!",
sound : "default"
}}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}}).then(function() {
// Set the job's success status
status.success("Job finished successfully.");
}, function(error) {
// Set the job's error status
status.error("Uh oh, something went wrong.");
});
参考: Push Notification Java Script guide
我的下一步是向20个查询(0< = day< 20)发送通知,并根据日期号码向每个查询发送消息。调用函数20次对我来说似乎很难看,我是否可以迭代,每次调用循环Parse.Push.send函数?
答案 0 :(得分:4)
我使用Parse.Promise.when(promises)
解决了我的问题承诺有点神奇,因为它们可以让你在没有嵌套的情况下链接它们。如果promise的回调返回一个新的promise,那么第一个将在第二个之前解析。这使您可以执行多个操作,而不会产生回调所带来的金字塔代码。
function scheduleWordsForDay(day)
{
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("day",day);
pushQuery.exists("deviceToken");
var promise = new Parse.Promise();
Parse.Push.send({
where: pushQuery,
data: {
alert : "word" + day
}}, { success: function() {
// Push was successful
},
error: function(error) {
}}).then (function(result){
//Marks this promise as fulfilled,
//firing any callbacks waiting on it.
promise.resolve(result);
}, function(error) {
//Marks this promise as fulfilled,
//firing any callbacks waiting on it.
promise.reject(error);
});
return promise;
}
Parse.Cloud.job("scheduleWordNotification", function(request, status)
{
var promiseArray = [];
for (var i = 0; i < 100; i++) {
var promise = scheduleWordsForDay(i);
promiseArray.push(promise);
}
//Returns a new promise that is
//fulfilled when all of the input promises are resolved.
Parse.Promise.when(promiseArray).then(function(result) {
console.log("success promise!!")
status.success("success promise!!");
}, function(error) {
console.error("Promise Error: " + error.message);
status.error(error);
});
});