0

I have a javascript function which always returns 'undefined'. Please help.

function GetUserInfo()
{
    Parse.Cloud.useMasterKey();
    var result;
    var query = new Parse.Query("UserInfo");
    query.equalTo("UserID", "1234");
    var run = query.find({
    success: function(results) {    
        result = results;
    },
    error: function(error) {
        result = error;
    }
  }); // find       
    return result;          
}

   var item = GetUserInfo();       // always return 'undefined'
  • Look very closely at your function `GetUserInfo` and see if you can find a place where it returns anything. (Hint: the return inside the callback is **not** a return from `GetUserInfo`.) The return value of a function is `undefined` if it has no explicit `return` statement. –  Nov 02 '14 at 05:18

1 Answers1

1

If a JavaScript function does not explicitly return a value, the value returned will always be undefined. In this case, you don't have a return statement for your GetUserInfo() function. There's a return statement in the query.find success callback, but that only returns within the scope of the callback, and does not return a value for the parent function.

If query.find is synchronous, you can assign the value of results to a variable created outside of your callback function. However, if query.find is asynchronous, you'll need to wait for the for the callback to run and return before your parent function can return a value.

Try stepping through your function, and logging the results of your query. That will give you a better idea of what's going on inside your function.

Patrick Coffey
  • 1,073
  • 8
  • 13
  • The cause of the problem is not that the callback may not return anything, it is that the `GetUserInfo` function is not returning anything. –  Nov 02 '14 at 05:19
  • That's precisely what I was saying. I'll update to clarify. :) – Patrick Coffey Nov 02 '14 at 05:23
  • I am sure the results.length is equal to 1. The statement 'GetUserInfo = results;' would return the result, wouldn't it? – Chuong Lam Nov 02 '14 at 05:47
  • @ChuongLam Afraid not. 1) The name of a JavaScript function doesn't represent its `return` value. 2) The other Q&A linked above explains this far more thoroughly, but `results` really can't be `return`ed from `GetUserInfo()`. With `query.find()` being asynchronous (in its own time), `GetUserInfo()` will actually exit and assign `item` before the `results` have become available. – Jonathan Lonowski Nov 02 '14 at 06:20
  • You are right. I just edited the code to make sure the query.find() completed and returned value. But it still not to work. Can you point out what is wrong? – Chuong Lam Nov 02 '14 at 06:36
  • @ChuongLam With asynchronous code, you'll want to become familiar with using callbacks (at least with current standards). Example: http://jsfiddle.net/a4fL6s6s/. – Jonathan Lonowski Nov 02 '14 at 06:42
  • Thanks Jonathan. Your code works wonderful. – Chuong Lam Nov 02 '14 at 07:53