我有一个云代码函数,它将 Notification 对象标记为“已读”,然后立即查询同一类以查找剩余的“未读”对象。
问题是大多数时间,我标记为已读的相同通知对象在我之前的未读查询中返回,即使值已在数据浏览器中更新。
当我从 Parse.Promise.when()
更改为 Parse.Object.saveAll()
时,问题就解决了,但仍不清楚原因。当所有 save()
操作完成时,应该解决 when promise ,因此不会运行最后一个“未读”查询,直到它们被标记为已读。
Parse.Object.saveAll(objects)
做了什么 Parse.Promise.when(promiseListOfSaves)
没有?
下面每个的代码示例。除了保存对象的方式外,两者之间没有太大区别。
Parse.Cloud.define('markThreadReadAndReturnUnreadCount', function(request, response){
var promiseChain = [];
var Notification = Parse.Object.extend("Notification");
qry = new Parse.Query(Notification);
qry.equalTo('owner', request.user);
qry.equalTo('read', false);
qry.equalTo('messageThreadId', request.params.threadId);
qry.find(null, {useMasterKey: true}).then(function(_notifications){
_.each(_notifications, function(_notification){
notification = new Notification();
notification.id = _notification.id;
notification.set('read', true);
promiseChain.push(notification.save(null, {wait: true}));
});
return Parse.Promise.when(promiseChain);
}).then(function(){
var countUnreadQuery = new Parse.Query(Notification);
countUnreadQuery.equalTo('owner', user);
countUnreadQuery.equalTo('read', false);
countUnreadQuery.find({useMasterKey: true}).then(function(results){
return response.success(results.length);
}
};
});
使用 Parse.Object.saveAll();
Parse.Cloud.define('markThreadReadAndReturnUnreadCount', function(request, response){
var saveObjects = [];
var Notification = Parse.Object.extend("Notification");
qry = new Parse.Query(Notification);
qry.equalTo('owner', request.user);
qry.equalTo('read', false);
qry.equalTo('messageThreadId', request.params.threadId);
qry.find(null, {useMasterKey: true}).then(function(_notifications){
_.each(_notifications, function(_notification){
notification = new Notification();
notification.id = _notification.id;
notification.set('read', true);
saveObjects.push(notification);
});
return Parse.Object.saveAll(saveObjects);
}).then(function(){
var countUnreadQuery = new Parse.Query(Notification);
countUnreadQuery.equalTo('owner', user);
countUnreadQuery.equalTo('read', false);
countUnreadQuery.find({useMasterKey: true}).then(function(results){
return response.success(results.length);
}
};
});
最佳答案
我不确定为什么 saveAll
在 when
不起作用的地方起作用,但我更喜欢 saveAll
而不是 when
在这种情况下有两个原因:
代码风格,下面两个选项哪个看起来更好:
function save(objects){ return Parse.Promise.when(objects.map(function(object){ return object.save(null, {wait: true}); })); } // or function save(objects){ return Parse.Object.saveAll(objects); }
性能,当你使用数组保存的时候,你发送了
n
个http请求来获取你想要保存的n
个对象,这是一个巨大的浪费资源,但是当您使用saveAll
时,您只为所有这些资源发送一个请求。
另外我认为您的第二个代码可以简化为:
...
qry.find(null, {useMasterKey: true}).then(function(_notifications){
_.each(_notifications, function(_notification){
notification.set('read', true);
});
return Parse.Object.saveAll(_notifications);
}).then(function(){
...
关于javascript - Parse.Object.saveAll(objects) 和 Parse.Promise.when(promiseListOfSaves) 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32985606/