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?