2014-10-09 4 views
6

objectId에서 사용자 개체를 가져 오려고합니다. 나는 그 objectId가 유효하다는 것을 안다. 그러나이 간단한 쿼리를 사용할 수 있습니다. 그게 뭐가 잘못 되었 니? 사용자는 쿼리 후 여전히 정의되지 않습니다.Parse Cloud Code objectId를 사용하여 사용자 검색

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; 
}; 

답변

20

약속을 사용한 빠른 클라우드 코드 예제입니다. 나는 거기에 몇 가지 문서를 가지고 있는데, 당신이 따라갈 수 있기를 바랍니다. 도움이 더 필요하면 알려주세요.

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; 
     } 
    }); 
}; 
+0

query.first() 메소드에 대해 알지 못했습니다. 고마워! –

+0

Parse.Cloud.useMasterKey(); 구문 분석 서버 버전 2.3.0 (2016 년 12 월 7 일)에서 더 이상 사용되지 않습니다. 그 버전부터는 아무 것도하지 않습니다 (아무 것도하지 않습니다). 이제 코드에서 ACL 또는 CLP를 재정의해야하는 각 메소드에 {useMasterKey : true} 선택적 매개 변수를 삽입해야합니다. – alvaro

0

이 문제는 구문 분석 쿼리가 비동기 적이라는 점에서 문제가 있습니다. 즉, 쿼리가 실행되기 전에 user (null)을 반환합니다. 사용자가 원하는 모든 작업을 성공의 내부에 넣어야합니다. 바라기를 나의 설명은 그것이 정의되지 않은 이유를 이해하는 데 도움이되기를 바랍니다.

Promises으로 조사하십시오. 첫 번째 쿼리에서 결과를 얻은 후에 뭔가를 호출하는 더 좋은 방법입니다.

+0

나는 성공에서 복귀하려고 시도했지만 작동하지 않았습니다. 나는 쿼리가 비동기라는 사실을 고려할 것이다. 나는 그것을 깨닫지 못했다. – Ben

+0

나머지 기능을 성공에 추가 할 수 있습니까? – Dehli

+0

성공 사례를 진행하기 위해 약속을 사용하려고 노력할 것입니다. – Ben

관련 문제