Parse JavaScript SDK and Promise Chaining
Parse JavaScript SDK and Promise Chaining
我在 Parse Cloud Code 中创建了一个后台作业,该作业根据我的一个 Parse 类中的日期发送电子邮件通知。
思路是:查询包含日期的类。遍历返回的每个对象并检查日期字段。如果日期等于今天,请发送电子邮件通知,将日期更改为 null 并将其保存回 Parse。
但是,似乎并非所有对象都保存回 Parse。 我怀疑这是我的承诺链的问题,但我很难诊断确切的问题或如何解决它。 以下是相关代码
Parse.Cloud.job("job", function(request, status) {
// Query for all users
var query = new Parse.Query(className);
query.each(function(object) {
if (condition) {
object.set(key, false);
object.save(null, {
success:function(object){
// This never executes!
},
error: function(error){
}
}).then(function(){
// This never executes
console.log("Save objects successful");
},
function(error){
status.error("Uh oh, something went wrong saving object");
});
// Set hiatus end successful
Mailgun.sendEmail({
});
}
});
});
objects.save() 承诺链中的这一行console.log("Save objects successful");
永远不会被执行 - 即使订阅对象成功保存到 Parse 也是如此。
此外,如果查询返回的对象超过 5 个,则只有前 5 个对象成功保存回 Parse。不会执行任何其他保存,也不会发送电子邮件通知。
我会按如下方式清理它,依靠 Promise.when ...
var savePromises = []; // this will collect save promises
var emailPromises = []; // this will collect email promises
// your code to setup the query here
// notice that this uses find() here, not each()
query.find(function(subscriptions) {
_.each(subscriptions, function(subscription) { // or a for loop, if you don't use underscore
// modify each subscription, then
savePromises.push(subscription.save());
// prepare each email then
var emailPromise = Mailgun.sendEmail({ /* your email params object here */ });
emailPromises.push(emailPromise);
});
// now do the saves
return Parse.Promise.when(savePromises);
}).then(function() {
// now do the emails
return Parse.Promise.when(emailPromises);
}).then(function() {
// Set the job's success status
status.success("Subscriptions successfully fetched");
// and so on with your code
您也可以考虑将保存和电子邮件合并到一个大的承诺数组中,但最好分两批连续进行,因为它们具有不同的失败模式。
相关文章:
- 使用promise和mongoose对文档进行排序
- 测试Angular Service解决错误回调中的promise
- 节点协同与生成器和Promise并行流量控制
- 根据是否解析了 Promise 从函数返回值
- 将一个方法转换为promise:Nodejs
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- js promise没有正确关闭
- Angularjs使用“;这个“;promise内的关键字回调
- AngularJS和promise值在调用本地函数时的效果-未定义
- 在ES6 Promise中,我应该在解决/拒绝之前使用return吗
- 以同步方式获取Javascript Promise的值
- NodeJS和pg promise,捕获PostgreSQL异常
- AngularJS使用http进行promise处理
- Angular promise return"未定义的“;值.NET MVC
- Promise函数在.then之后未运行函数化
- 如何为javascript promise进行阻塞并返回解析结果
- JavaScript: Promise chaining in foreach loop
- Parse JavaScript SDK and Promise Chaining
- Factory - Then and Catch Promise Chaining in AngularJS
- 理解angular$q promise chaining w.r.t特定示例