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


i trying write basic program work this:

enter name: _ enter age: _  name <name> , age <age>. 

i've been trying figure out how in node without using prompt npm module.

my attempt @ was:

import readline 'readline'  const rl = readline.createinterface({   input: process.stdin,   output: process.stdout })  rl.question('what name? ', (name) => {   rl.question('what age? ', (age) => {     console.log(`your name ${name} , age ${age}`)   }) }) 

however, nested way of doing seems weird, there anyway can without making nested right order?

zangw's answer sufficient, think can make clearer:

import readline 'readline'  const rl = readline.createinterface({   input: process.stdin,   output: process.stdout })  function askname() {   return new promise((resolve) => {     rl.question('what name? ', (name) => { resolve(name) })   }) }  function askage(name) {   return new promise((resolve) => {     rl.question('what age? ', (age) => { resolve([name, age]) })   }) }  function outputeverything([name, age]) {   console.log(`your name ${name} , age ${age}`) }  askname().then(askage).then(outputeverything) 

if don't care wether ask both questions sequentially, do:

//the other 2 stay same, don't need name or arrays function askage() {   return new promise((resolve) => {     rl.question('what age? ', (age) => { resolve(age) })   }) }  promise.all([askname, askage]).then(outputeverything) 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -