Node.js - Return a value in a function

by
Jeremy Canfield |
Updated: July 22 2024
| Node.js articles
This assumes you are familiar with Node.js. If not, check out my article FreeKB - Node.js - Creating your first Node.js Hello World app on Linux.
In this example, the function named "foo" returns 'Hello'.
function foo() {
return 'Hello';
}
const greeting = foo();
console.log(greeting);
Or like this, using const.
const foo = function() {
return 'Hello';
}
const greeting = foo();
console.log(greeting);
async function
Fundamental to Node.js is the concept of asynchronous which is the idea of doing multiple things simultaenously. The async keyword can be used so that you immediately move through the script without waiting for a response from the async function.
async function Hello(greeting) {
return await greeting;
}
console.log(Hello("Hello World"));
Now running the script should return the following.
~]$ node app.js
Promise { 'Hello World' }
.then is used if you want the value being returned by the async function.
async function Hello(greeting) {
return await greeting;
}
Hello("Hello World").then(response => {console.log(response)});
Which should print "Hello World".
~]$ node app.js
Hello World
Or, more commonly, with .then and .catch.
async function Hello(greeting) {
return await greeting;
}
Hello("Hello World")
.then(response => {console.log(response)})
.catch(err => {console.error(err)});
Did you find this article helpful?
If so, consider buying me a coffee over at