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?
NodeJs is single threaded, so we should not block process.
in your case you have two options 1. passing callback 2. using Promise library (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
Ex 1: passing callback
function fetchUser(username, callback)
{
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.");
callback(null,results)
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
callback(error)
}
});
}
Client code:
function test()
{
var user = fetchUser("example", function(error, user){
if(error){
console.error(error)
}else {
console.log(user)
}
});
}
Ex 2: Using Promising library
function fetchUser(username){
return new Promise(function(resolve, reject){
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.");
resolve(results)
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
reject(error)
}
});
})
}
Client code:
function test()
{
fetchUser("example")
.then(function(user){
console.log(user)
})
.catch(function(error){
console.error(error)
})
}