当使用串行 Promise 时,我对在哪里放置 response.success() 有点困惑。
情况如下:我有一个云函数,它接受电子邮件地址数组和当前用户。该函数执行以下操作:
- 根据用户对象 ID 查找当前用户。
- 迭代电子邮件地址数组
- 查找每个给定电子邮件地址是否有现有用户
- 如果存在现有用户,我们会检查现有用户和当前用户是否是好友
- 即使他们不是 friend ,也会建立友谊。
现在,当我在没有 response.success() 的情况下运行此函数时,它完全按照我的预期进行操作,并且创建了友谊条目。但无论我将响应放在代码中的哪个位置,我都会收到结果response.success 消息,并且不会执行任何序列化的 promise 。
为什么最终的成功/失败很重要:我正在从 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");
});
});
提前致谢。如果还有什么我可以补充的,请告诉我。
最佳答案
附加到promise
的.then
回调函数应该返回一个promise。忽略这一点是使用 Promise 时的一个常见错误。
此外,Parse 似乎不像浏览器那样使用 console.log
显示对象,因此我将它们包装到 JSON.stringify()
中。
关于javascript - 串行 promise 和响应。云代码中的成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21252145/