As the method executeQueryAsync
indicates it is asynchronous.
You can actually force the XMLHttpRequest to be synchronous, although that is beside the point.
What you are looking for is a callback function, something like this:
var getSpCurrentUser = function(callback) {
var ctx = new SP.ClientContext.get_current();
var user = ctx.get_web().get_currentUser();
ctx.load(user);
ctx.executeQueryAsync(function() {
callback(null, user);
}, function(a, b) {
callback(new Error(b.get_message()));
});
};
getSpCurrentUser(function(error, user) {
if (error) {
console.error(error);
return;
}
console.log(user.get_title());
});