Empowering you to understand your world

Node.js Code Example: How To Get A Value From An Asynchronous Function In Node.js

Screenshot of a callback function returning a value
A screenshot of a callback function returning a value in Node.js (in the WebStorm IDE).

If you’re trying to get a return value from an asynchronous callback function in Node.js before you continue execution, there is a way to do it without having to use async.wait or convert it to a synchronous function.

You would pass a function (in this code sample, the function is named ‘callbackfunc’) containing the code you want executed after the asynchronous operation is complete as a parameter to that function as shown below.

In this case, the asynchronous operation is a MongoDB database query that pulls up the record of a certain user. The function being passed around (‘callbackfunc’) is highlighted in purple.

GetRecord('nicholasbrown29', function(returneddata)  {
    console.log('Variable contents: ' + returneddata); //returneddata contains the parameter passed by the 'callbackfunc' call below.
});
//Asynchronous: Get a record from a MongoDB database.
function GetRecord(nameofuser, callbackfunc) {
    Record.find({UserName: nameofuser}, function (error, datatoreturn) {
        callbackfunc(datatoreturn); //Executes the callback function found in the GetRecord method call above.
    });
}

This is also useful if you want to write a getter function that gets data from a PostgreSQL database, ensuring that your getter code is executed only after the database query operation is complete. This will enable you to avoid ‘undefined’ return values because your code executed before the database operation is completed.

Leave a Reply

Subscribe to our newsletter
Get notified when new content is published