问题描述:

How do you add a user to an existing role when they're signing up? My code below doesn't work, I don't get any errors or any prints in the logs (not sure what I'm doing wrong):

Parse.User.signUp(req.body.email, req.body.password, {

"name": req.body.name,

"email": req.body.email,

}, {

success: function(user) {

var query = new Parse.Query(Parse.Role);

query.equalTo("name", 'Basic User');

query.find({

success: function(roles) {

alert("HELLO" + roles);

if (roles.length < 1) {

alert("HELLO");

console.log("Error Signing Up: No roles for " + signUpRoleGroup + " were found");

} else {

alert("HERE");

roles[0].getUsers().add(user);

roles[0].save();

}

},

error: function(error) {

alert("Could not add users to the account " + accountName + " error: " + error.message);

}

});

},

error: function(user, error) {

alert("Error signing up user");

}

});

网友答案:

I think what's going on is the caller isn't giving this function a chance to finish saving the role. The cloud function should wait until the role is saved before invoking response.success() or error().

Here's a promise-returning rewrite of the same code. Easier on the eyes, I think, and clearer about asynch tasks done serially. This puts you in more firm control of the response.

Parse.Cloud.define("signupAsBasicUser", function(request, response) {
    signupAsBasicUser(req.body.name, req.body.password, req.body.email).then(function(user) {
        response.success(user);
    }, function(error) {
        response.error(error);
    });
});


// return a promise fulfilled with a signed-up user who is added to the 'Basic User" role
//
function signupAsBasicUser(name, password, email) {
    var user = new Parse.User();
    user.set("username", name);
    user.set("password", password);
    user.set("email", email);
    return user.signUp().then(function() {
        var query = new Parse.Query(Parse.Role);
        query.equalTo("name", 'Basic User');
        return query.find();
    }).then(function(roles) {
        if (roles.length < 1) return Parse.Promise.error("no such role");
        roles[0].getUsers().add(user);
        return roles[0].save();
    }).then(function() {
        return user;
    });
}
相关阅读:
Top