JVG
JVG

Reputation: 21170

Javascript - Making a function asynchronous

I'm building an app with Node.js for the first time, and a little confused about asynchronous functions. I'm getting better at recognising when something won't work because of async, but still unsure how to remedy it.

Here's my function:

function titleCase(element){
    var string = element.replace(/([^\W_]+[^\s-]*) */g, function(txt){
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        })
    element = string;
}
var 1 = "UPPER CASE"; var2 = "lower case"; var3 = "MiXeD CaSe";
titleCase(var1);
titleCase(var2);
titleCase(var3);

console.log(var1 + " " + var2 + " " + var3);
}

(the function should take a string and give it title case).

Currently when the code runs, I get

UPPER CASE lower case MiXeD CaSe

so clearly the console.logis happening before the titleCase function is firing properly. I know one solution is to not use the function and just call the string replace 3 times for each variable, but I want to learn to do it asynchronously.

What's the best way to achieve this, to ensure that the console.log function ONLY fires after all 3 titleCase functions have been completed?

Upvotes: 0

Views: 211

Answers (2)

user2487119
user2487119

Reputation:

Node.js is a way to use JavaScript at a server-side in way of processing request via handlers on events (request is an event).

Your block of code has nothing to do with it. Seems like you are missing the conception so far.

However to run your example try:

function titleCase(txt){
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();

}
var var1 = "UPPER CASE"; var2 = "lower case"; var3 = "MiXeD CaSe";
var1 = titleCase(var1);
var2 = titleCase(var2);
var3 = titleCase(var3);

console.log(var1 + " " + var2 + " " + var3);

Please notice that there is no "pass by reference" features in js, so you shoud use constructions like

var1 = titleCase(var1)

instead of

titleCase(var1)

Hope it would be helpfull

Upvotes: 1

Evan Trimboli
Evan Trimboli

Reputation: 30092

It's got nothing to do with async, variable assignment doesn't work like that. element is a local variable to your titleCase function, so doing that assignment doesn't have any effect outside the function. You need to return a value:

function titleCase(element) {
    return element.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });

}

var var1 = "UPPER CASE";
var var2 = "lower case";
var var3 = "MiXeD CaSe";
var1 = titleCase(var1);
var2 = titleCase(var2);
var3 = titleCase(var3);

console.log(var1, var2, var3); 

Upvotes: 2

Related Questions