Repeating console output - where do I need to insert my callback?

This is my code:

var databaseUrl = "mydb";
var collections = ["users", "reports"];
var db = require("mongojs").connect(databaseUrl, collections);

newuser =       {
            email: "john@example.com",
            password: "iLoveMongo",
            sex: "male"
        };


saveuser = function(user, callback) {
    db.users.save(
        user,
        function( error, saved) {
            if( error || !saved )
                console.log( "User not saved");
            else 
                console.log( "User saved" );
                callback();
        }
    );
};

removeuser = function() {
    db.users.remove(
        {
            sex: "male"
        },
        function( error, removed)   {
            if( error || !removed )
                console.log( "User not deleted");
            else 
                console.log( "User deleted" );
        }
    );
};

finduser = function() {
    db.users.find(
        {
            sex: "male"
        },
        function(error, users) {
            if( error || !users.length )
                console.log( "No male Users found");
            else 
            {
                console.log( "male Users found" );
                users.forEach(
                    function(maleUser) {
                        console.log(maleUser);
                    }
                );
            }
        }
    )
};

updateuser = function() {
    db.users.update(
        {
            email: "john@example.com"
        },
        {
            $set: { password: "iReallyLoveMongo" }
        },
        function(err, updated) {
            if( err || !updated )
                console.log("User not updated");
            else
                console.log("User updated");
        }
    );  
}

var options = {
    1: { 
        option: "Save a User",
        execute: saveuser.bind(null, newuser, finduser)
    },
    2: { 
        option: "Remove a User",
        execute: removeuser
    },
    3: { 
        option: "Find a User",
        execute: finduser
    },
    4: { 
        option: "Update a User",
        execute: updateuser
    }
}
function read() {
    console.log("");
    console.log(" Enter your choice: ");

    stdin = process.stdin;
    stdin.setEncoding('utf8');
    stdin.on('data', choice);
};

function choice (data) {
    data = parseInt(data);

    console.log("You entered: " + data);
    console.log("You choose to do: " + options[data]["option"]);
    options[data]["execute"]();
};

read();

What happens, only with the first command the text "Enter your choice" appears. You can still enter numbers and make another option.

This is what I get on the console:

PS C:\Users\Benni\Documents\nodejs> node .\mongotest\app.js

 Enter your choice:
1
You entered: 1
You choose to do: Save a User
User saved
male Users found
{ _id: 5386ba18463a008011fe6213,
  email: 'john@example.com',
  password: 'iLoveMongo',
  sex: 'male' }
3
You entered: 3
You choose to do: Find a User
male Users found
{ _id: 5386ba18463a008011fe6213,
  email: 'john@example.com',
  password: 'iLoveMongo',
  sex: 'male' }

I want that after each successful command (after options[data]["execute"]()), "Enter your choice" appears again. Like this:

PS C:\Users\Benni\Documents\nodejs> node .\mongotest\app.js

 Enter your choice:
1
You entered: 1
You choose to do: Save a User
User saved
male Users found
{ _id: 5386ba18463a008011fe6213,
  email: 'john@example.com',
  password: 'iLoveMongo',
  sex: 'male' }

 Enter your choice:
3
You entered: 3
You choose to do: Find a User
male Users found
{ _id: 5386ba18463a008011fe6213,
  email: 'john@example.com',
  password: 'iLoveMongo',
  sex: 'male' }

Where do I need to call read () again? If I put it at the end choice, "Enter your choice" will appear options[data]["execute"]();. If I put it at the end read, I get an infinite loop cycle / Maximum call stack size.

Or can I add a callback to options[data]["execute"]();? Sort of

function( null, read){
  options[data]["execute"]();
};

?

+4
3

, , , . , , , , . , , . , , :

newuser =       {
            email: "john@example.com",
            password: "iLoveMongo",
            sex: "male"
        };


saveuser = function(user, callback) {
    db.users.save(
        user,
        function( error, saved) {
            if( error || !saved )
                callback( "User not saved");
            else                 
                callback(saved);
        }
    );
};

removeuser = function(callback) {
    db.users.remove(
        {
            sex: "male"
        },
        function( error, removed)   {
            if( error || !removed )
                callback( "User not deleted");
            else 
                console.log( "User deleted" );
                callback();
        }
    );
};

finduser = function(callback) {
    db.users.find(
        {
            sex: "male"
        },
        function(error, users) {
            if( error || !users.length )
                callback( "No male Users found");
            else 
            {
                console.log( "male Users found" );
                callback(null, users);
            }
        }
    )
};

updateuser = function(callback) {
    db.users.update(
        {
            email: "john@example.com"
        },
        {
            $set: { password: "iReallyLoveMongo" }
        },
        function(err, updated) {
            if( err || !updated )
                callback("User not updated");
            else
                console.log("User updated");
                callback(null, updated);
        }
    );  
}

var options = {
    1: { 
        option: "Save a User",
        execute: saveuser.bind(null, newuser)
    },
    2: { 
        option: "Remove a User",
        execute: removeuser
    },
    3: { 
        option: "Find a User",
        execute: finduser
    },
    4: { 
        option: "Update a User",
        execute: updateuser
    }
}
function read() {
    console.log("");
    console.log(" Enter your choice: ");

    stdin = process.stdin;
    stdin.setEncoding('utf8');
    stdin.on('data', choice);
};

function choice (data) {
    data = parseInt(data);

    console.log("You entered: " + data);
    console.log("You choose to do: " + options[data]["option"]);
    options[data]["execute"](function(err, res){
        if(err){
            console.log(err);                
        }
        if(res){
            if(Array.isArray(res)){
                res.forEach(function(item){
                    console.log(item);
                })
            } else {
                console.log(res);
            }
        }
        console.log(" Enter your choice: ");
    });
};

read();

Promises

promises. , , , .

Q Promises , , . , Q .

, , -, . Q.ninvoke, , , .

var Q = require('q');
saveUser = function(user) {
    return Q.ninvoke(db.users,"save", user)
        .then(function(user){
            console.log("User saved: %j", user);
        })
        .catch(function(error){
            console.log("Error while saving: %s", error);
        });
};

removeUser = function() {
    return Q.ninvoke(db.users,"remove", {sex: "male"})
        .then(function(result){
            console.log("User removed: %j", result);
        })
        .catch(function(error){
            console.log("Error while removing: %s", error);
        });
};

findUser = function() {
    return Q.ninvoke(db.users,"find", {sex: "male"})
        .then(function(user){
            console.log("User found: %j", user);
        })
        .catch(function(error){
            console.log("Error while finding: %s", error);
        });
};

updateUser = function() {
    return Q.ninvoke(db.users,"update", 
        {
            email: "john@example.com"
        },
        {
            $set: { password: "iReallyLoveMongo" }
        })
        .then(function(user){
            console.log("User updated: %j", user);
        })
        .catch(function(error){
            console.log("Error while updating: %s", error);
        });
};

, -, .

, , :

function read() {
    console.log("");
    console.log(" Enter your choice: ");

    stdin = process.stdin;
    stdin.setEncoding('utf8');
    stdin.on('data', choice);
};

function choice (data) {
    data = parseInt(data);

    console.log("You entered: " + data);
    console.log("You choose to do: " + options[data]["option"]);
    options[data]["execute"]().then(function(){
        console.log("Enter your choice: ")
    });
};

read();

, [data] [ "execute" ] . , " ".

voila:

Enter your choice: 
1
You entered: 1
You choose to do: Save a User
User saved: [{"email":"john@example.com","password":"iLoveMongo","sex":"male","_id":"5388f57035a2eda13b7e4ea7"},{"n":0}]
Enter your choice: 
2
You entered: 2
You choose to do: Remove a User
User removed: {"n":2}

, .

+1
function choice (data) {
    data = parseInt(data);

    console.log("You entered: " + data);
    console.log("You choose to do: " + options[data]["option"]);
    options[data]["execute"]();

     process.nextTick(function(){
       console.log("");
       console.log(" Enter your choice: ");
     });    
};
0

You can study the readline built-in to help you with this:

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function choiceHandler(choice) {
  choice = parseInt(choice, 10);
  if (isNaN(choice))
    console.log('Bad choice, try again');
  else {
    console.log('You entered: ' + choice);
    console.log('You chose to do: ' + options[choice]['option']);
  }
  rl.prompt();
}

console.log('');
rl.setPrompt(' Enter your choice: ');
rl.on('line', choiceHandler);
rl.prompt();
0
source

Source: https://habr.com/ru/post/1542296/


All Articles