我正在尝试拍摄照片对象列表,并根据拍摄日期将它们分配到图库。诀窍在于,在流程执行之前,可能根本没有画廊(即 - 代码需要为当天拍摄当天拍摄的照片时没有画廊的一天创建新画廊。)
这是我的代码:
var Photo = Parse.Object.extend("Photo");
var Gallery = Parse.Object.extend("Gallery");
var query = new Parse.Query(Photo);
query.equalTo("owner", Parse.User.current());
query.find().then(function(results) {
// Create a trivial resolved promise as a base case.
var promise = Parse.Promise.as();
for (photo in results)
{
var photoObject = results[photo];
//Closure to encapsulate the photo object represented by this loop iteration
//(function(photo) {
promise = promise.then((function(photo) {
console.log('iterator: ' + photo.id);
var takenAt = photo.get("takenAt");
var dd = takenAt.getDate();
var mm = takenAt.getMonth()+1; //January is 0!`
var yyyy = takenAt.getFullYear();
var dateOf = new Date(yyyy+"-"+mm+"-"+dd);
var query = new Parse.Query(Gallery);
query.equalTo("owner", Parse.User.current());
query.equalTo("dateOf", dateOf);
query.find().then(function(galleries) {
console.log("Galleries:"+galleries.length);
if (galleries.length > 0)
{
photo.addUnique("galleries",galleries[0]);
photo.save();
}
else
{
var gallery = new Gallery();
gallery.set("owner",Parse.User.current());
gallery.set("dateOf",dateOf);
return gallery.save();
}
}).then(function(gallery) {
//Finished new gallery save!
photo.addUnique("galleries",gallery);
photo.save();
});
})(photoObject));
}
return promise;
//console.log(photo.get("takenAt"));
}).then(function() {
// Every photo was added to the proper gallery.
});
问题是当它运行时,我得到以下输出(在后端运行Express / Node.js服务器,这是控制台输出):
I2014-10-03T19:08:24.934Z]iterator: bZJ1Ke0QXO
I2014-10-03T19:08:24.936Z]iterator: 6li2Ztxhrd
I2014-10-03T19:08:24.937Z]iterator: FfUCwgNsts
I2014-10-03T19:08:24.937Z]iterator: fJdAeqCwYW
I2014-10-03T19:08:24.939Z]iterator: ChUmgipm7d
I2014-10-03T19:08:24.942Z]iterator: 9MiTFHxLzh
I2014-10-03T19:08:24.942Z]iterator: bWZAbNiNB2
I2014-10-03T19:08:24.943Z]iterator: RQqe3NyAxK
I2014-10-03T19:08:24.991Z]Galleries:0
I2014-10-03T19:08:25.043Z]Galleries:0
I2014-10-03T19:08:25.045Z]Galleries:0
I2014-10-03T19:08:25.095Z]Galleries:0
I2014-10-03T19:08:25.146Z]Galleries:0
I2014-10-03T19:08:25.147Z]Galleries:0
I2014-10-03T19:08:25.253Z]Galleries:0
I2014-10-03T19:08:25.305Z]Galleries:0
因此,您可以看到正在创建的第一个图库在检查完所有照片后发生,问题是它在同一天创建了8个图库(样本集中的所有照片都是在同一天拍摄的)。 / p>
看起来承诺没有按照我的预期连续执行。如何强制这些调用按顺序发生,以便第二次照片查找在第一次完成创建图库后才会发生(如果需要)?