[英]Javascript - Making a function asynchronous
I'm building an app with Node.js for the first time, and a little confused about asynchronous functions. 我是第一次使用Node.js构建应用程序,并且对异步函数有些困惑。 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.log
is happening before the titleCase
function is firing properly. 因此很明显,在
titleCase
函数正确触发之前, console.log
正在发生。 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. 我知道一种解决方案是不使用该函数,而仅对每个变量调用3次字符串替换,但是我想学习异步地做。
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? 确保此最佳方法是什么,以确保仅在完成所有3个
titleCase
函数之后才启动console.log
函数?
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. element
是titleCase
函数的局部变量,因此执行该赋值对函数外部没有任何影响。 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);
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). Node.js是在服务器端使用JavaScript的一种方式,它通过事件处理程序(请求是事件)来处理请求。
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 请注意,js中没有“按引用传递”功能,因此您应该使用类似
var1 = titleCase(var1)
instead of 代替
titleCase(var1)
Hope it would be helpfull 希望对您有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.