最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to use promises for this example? - Stack Overflow

programmeradmin1浏览0评论

I am basically trying to write a very basic program that will work like this:

Enter your name: _
Enter your age: _

Your name is <name> and your age is <age>.

I've been trying to figure out how to do something like this in Node without using the prompt npm module.

My attempt at this was:

import readline from 'readline'

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

rl.question('What is your name? ', (name) => {
  rl.question('What is your age? ', (age) => {
    console.log(`Your name is ${name} and your age is ${age}`)
  })
})

However, this nested way of doing it seems weird, is there anyway I can do it without making it nested like this to get the right order?

I am basically trying to write a very basic program that will work like this:

Enter your name: _
Enter your age: _

Your name is <name> and your age is <age>.

I've been trying to figure out how to do something like this in Node without using the prompt npm module.

My attempt at this was:

import readline from 'readline'

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

rl.question('What is your name? ', (name) => {
  rl.question('What is your age? ', (age) => {
    console.log(`Your name is ${name} and your age is ${age}`)
  })
})

However, this nested way of doing it seems weird, is there anyway I can do it without making it nested like this to get the right order?

Share Improve this question edited Jan 16, 2016 at 1:27 Saad asked Jan 16, 2016 at 0:56 SaadSaad 53.8k21 gold badges76 silver badges114 bronze badges 2
  • In addition consider looking at the docs for readline. – jmunsch Commented Jan 16, 2016 at 1:13
  • Thanks very much for the recommendation! I was able to shorten the code to what I now have above, I just wanted to ask if there a way to get rid of this nested structure I have to use to get the right order of questions? Is this what promises are for? If so, do you know how I could transform the above to use promises? – Saad Commented Jan 16, 2016 at 1:22
Add a comment  | 

3 Answers 3

Reset to default 17

zangw's answer would be sufficient, but I think I can make it clearer:

import readline from 'readline'

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

function askName() {
  return new Promise((resolve) => {
    rl.question('What is your name? ', (name) => { resolve(name) })
  })
}

function askAge(name) {
  return new Promise((resolve) => {
    rl.question('What is your age? ', (age) => { resolve([name, age]) })
  })
}

function outputEverything([name, age]) {
  console.log(`Your name is ${name} and your age is ${age}`)
}

askName().then(askAge).then(outputEverything)

if you don't care about wether it ask both questions sequentially, you could do:

//the other two stay the same, but we don't need the name or the arrays now
function askAge() {
  return new Promise((resolve) => {
    rl.question('What is your age? ', (age) => { resolve(age) })
  })
}

Promise.all([askName, askAge]).then(outputEverything)

Here is one example with Q

var readline = require('readline');
var Q = require('q');

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

var q1 = function () {
    var defer = Q.defer();
    rl.question('What is your name? ', (name) => {
        defer.resolve(name);
    }); 

    return defer.promise;
};

q1().then(function(name) {
    rl.question('What is your age? ', (age) => {
        console.log(`Your name is ${name} and your age is ${age}`)
    });
});

Or with simple Promise

function question1() {
    return new Promise(function(resolve) {
        rl.question('What is your name? ', (name) => {
            resolve(name);
        });         
    });

};

question1().then(function(name) {
    rl.question('What is your age? ', (age) => {
        console.log(`Your name is ${name} and your age is ${age}`)
    });    
});

There is a way to do it without promises.

rl.question('What is your name? ', getUserName);

function getUserName (name) {
    rl.question('What is your age? ', getUserAge(name));  
}

function getUserAge (name) {
    return function (age) {
        console.log(`Your name is ${name} and your age is ${age}`)
    }
}

See, no nesting but properly refactored functions. You can and should do the same with api's that return promises. Anonymous functions is a nice feature of the language but that doesn't mean you must use it for everything.

发布评论

评论列表(0)

  1. 暂无评论