Parse Cloud Code - getting user using objectId

I am trying to get a user object from objectId. I know that objectId is valid. But I can make this simple request work. What is wrong with it? the user is still undefined after the request.

var getUserObject = function(userId){ Parse.Cloud.useMasterKey(); var user; var userQuery = new Parse.Query(Parse.User); userQuery.equalTo("objectId", userId); userQuery.first({ success: function(userRetrieved){ console.log('UserRetrieved is :' + userRetrieved.get("firstName")); user = userRetrieved; } }); console.log('\nUser is: '+ user+'\n'); return user; }; 
+6
source share
2 answers

An example of fast cloud code using promises. I have documentation there, hope you can follow. If you need more help let me know.

 Parse.Cloud.define("getUserId", function(request, response) { //Example where an objectId is passed to a cloud function. var id = request.params.objectId; //When getUser(id) is called a promise is returned. Notice the .then this means that once the promise is fulfilled it will continue. See getUser() function below. getUser(id).then ( //When the promise is fulfilled function(user) fires, and now we have our USER! function(user) { response.success(user); } , function(error) { response.error(error); } ); }); function getUser(userId) { Parse.Cloud.useMasterKey(); var userQuery = new Parse.Query(Parse.User); userQuery.equalTo("objectId", userId); //Here you aren't directly returning a user, but you are returning a function that will sometime in the future return a user. This is considered a promise. return userQuery.first ({ success: function(userRetrieved) { //When the success method fires and you return userRetrieved you fulfill the above promise, and the userRetrieved continues up the chain. return userRetrieved; }, error: function(error) { return error; } }); }; 
+20
source

The problem is that Parse requests are asynchronous. This means that it will return the user (null) before the request has time to execute. No matter what you want to do with the user, you need to be sure of success. I hope my explanation helps you understand why it is undefined.

See Promises . This is the best way to call something after getting the result from the first query.

0
source

Source: https://habr.com/ru/post/976526/


All Articles