Ad

Is It Possible To Use Promises For This Example?

- 1 answer

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?

Ad

Answer

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)
Ad
source: stackoverflow.com
Ad