user20072008
user20072008

Reputation: 379

NodeJS & Express - Correct method to write this code

This nodejs / express code works perfectly fine but I dont like idea of passing response object in create_new_user function. I want to return a value from create_new_user function but it does not return using res.send or res.sendStatus. I did this but I dont think this is the right approach. Can you please help me to understand what exactly is going wrong and what is the best way to do it ?

var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var async = require('async');

router.post('/', function(req, res, next){

        var uname = req.body.user;
        var city = req.body.city;

            async.series([
                function(callback){
                    create_new_user(uname, city, res);
                    console.log(' First Function');
                    callback();
                },
                function(callback){
                    console.log(' Second Function');
                    callback(); 
                }
                ], function(){
                    console.log("Execution FInished");
            });
});

function create_new_user(username , city, res){

    var con = mysql.createConnection({

                host:'localhost',
                user:'root',
                password:'admin',
                database:'test'
            });

    var q = " INSERT INTO user_master VALUES (null, ? , ? ) ";
    var field_values = [ username, city]; 

    con.query(q, field_values, function(err, results){

        if(err){
            throw err;
        }
        else{
            console.log("Last Id : " + results.insertId);
            res.send(results.insertId); /* see this */
        }

    });
    con.end();
}
module.exports = router;

Upvotes: 0

Views: 51

Answers (1)

Matthew Arkin
Matthew Arkin

Reputation: 4648

Node operates on a async-io principle so anything that involves reading or writing on some external service (like a database or a web request), happens asynchronously. As a result, asynchronous functions don't return values, they normally just return some sort of callback function.

Instead of passing res, you could pass some function as the last parameter. Create_new_user would then call that function and pass the result of the database call to it.

Alternatively, a popular approach to this callback issue is to use Promises. Create_new_user would return a promise that gets fulfilled when the database call completes. Then another function would get run when the promise is fulfilled.

Upvotes: 2

Related Questions