We are writing server code in nodejs and using Parse javascript sdk. Often we need to fetch or update various Parse objects. For example, fetch a user with username 'Example'.
  function fetchUser(username)
  {
      var User = Parse.Object.extend("User");
      var query = new Parse.Query("User");
      query.equalTo("username",username);
      query.first({
        success: function(results) {
        console.log("Successfully retrieved " + results.length + " scores.");
        return results;
      },
      error: function(error) {
        console.log("Error: " + error.code + " " + error.message);
      }
     });
  }
This function might be called by some other function:
function test()
{
    var user = fetchUser("example");
    console.log(user); // would often print undefined
    return user;
}
function top()
{
    // some code
    var user = test();
    //some code
}
// and the function top() mmight be called by some other functions
The problem is that I would get undefined results because the find/first operations runs asynchronously. Is there any way to ensure that fetchUser() function returns only when the find/first operation is successful/complete?
JavaScript is asynchronous by its nature. You have to pass a callback to the fetchUser() function and rewrite your client code to something like this:
function fetchUser(username, callback) {
    // do request and call callback(null, user) on success
    // or callback(some_error_object) on failure.
}
function test(callback) {
    var onFetched = function(err, user) {
        console.log(user);
        callback(err, user);
    }
    var user = fetchUser("example", onFetched);
}
Also you can use promises or generators (since EcmaScript 6) approaches.
UPD: Although some APIs (DB drivers, fs and so on) allow one to use them in a synchronous manner, it's considered as bad way to write a code in JavaScript. Since JS runs your code in a single thread, blocking this thread by using synchronous calls will block all other tasks. So, if you develop a web server that handles a few clients simultaneously and decided to use synchronous calls to some API, only one client at a time will be served while other clients will be in a pending state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With