Say I'm creating a simple CLI. I want to use native node readline module to take in some input from user at prompt. I thought of this :

var prompt = chalk.bold.magenta;
var info = {};

rl.question(prompt('Thing One : '), function(args) {
    info.one = args;
    rl.question(prompt('Thing Two : '), function(args) {
        info.two = args;
        rl.question(prompt('Thing Three : '), function(args) {
            info.three = parseInt(args);
            rl.close();
            runSomeOtherModuleNow();
        })
    })
});

This does seem to work in a way I'd like, but this seems like a bad approach. I'd much prefer a flatter code than a pyramid like this.

Any suggestions are welcome!

share|improve this question
1  
Use promises, maybe with async/await. – gcampbell Jul 6 '16 at 13:35

Flow Control libraries such as Async.js exist for exactly that. With async, your code can become:

var async = require('async');
var prompt = chalk.bold.magenta;
var info = {};

async.series([
    (callback) => {
        rl.question(prompt('Thing One : '), function(args) {
            info.one = args;
            callback();
        }
    },
    (callback) => {
        rl.question(prompt('Thing Two : '), function(args) {
            info.two = args;
            callback();
        }
    },
    (callback) => {
        rl.question(prompt('Thing Three : '), function(args) {
            info.three = parseInt(args);
            callback();
        }
    }
], () => {
    rl.close();
    runSomeOtherModuleNow();
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.