在使用串行Promise时,我对放置 response.success()的位置感到有些困惑。
情况就是这样:我有一个云功能,接受一系列电子邮件地址和当前用户。该功能执行以下操作:
现在,当我在没有 response.success()的情况下运行此函数时,它完全符合我的预期,并创建了友谊条目。但无论我在哪里将响应放在代码中,我都会得到生成的response.success消息,并且没有任何序列化的promises执行。
为什么最终的成功/失败很重要:我正在从iOS应用程序执行此功能,我想在iOS端正确处理成功或失败案例。
这是云功能:
Parse.Cloud.define("friendExistingUsers", function(request, response) {
// Get our parameters
var addresses = request.params.emailAddresses;
var userId = request.params.user;
// Query for our user
var userQuery = new Parse.Query("User");
userQuery.equalTo("objectId", userId)
userQuery.first().then(function(currentUser) {
// if we find the user, walk the addresses
var promise = Parse.Promise.as("success");
_.each(addresses, function(address) {
console.log(address);
// add a then to our promise to handle whether a relationship is
// being created.
promise = promise.then(function() {
// find if there is a user for that address
var emailQuery = new Parse.Query("User");
emailQuery.equalTo("email", address);
emailQuery.first().then(function(addressUser) {
if (typeof addressUser != 'undefined') {
// found one.
console.log(addressUser);
// figure out if our current user and this user are
// friends.
var friendQuery = new Parse.Query("FVFriendship");
friendQuery.equalTo("from", currentUser);
friendQuery.equalTo("to", addressUser);
friendQuery.first().then(function(relationship) {
if (typeof relationship != 'undefined') {
// if they are, we need to pass.
console.log("Found a relationship: " = relationship)
} else {
// They are not. Add the friendship
var Friendship = Parse.Object.extend("FVFriendship");
var friendship = new Friendship();
friendship.set("from", currentUser);
friendship.set("to", addressUser);
friendship.save().then(function(result) {
console.log("Created a friendship: " + result)
});
};
});
} else {
// we did not find a user for that address
console.log("No user for " + address);
};
});
});
});
console.log(promise);
return promise;
}).then(function() {
response.success("success");
});
});
先谢谢。如果还有什么我可以补充的,请告诉我。
答案 0 :(得分:0)
.then
附加的promise
回调函数应返回承诺。使用promises时,错过这是一个常见的错误。
Parse似乎没有像浏览器那样显示console.log
的对象,所以我将它们包装到JSON.stringify()
中。