这个例子可以使用promises吗?

saa*_*adq 10 javascript node.js

我基本上试图编写一个非常基本的程序,它将像这样工作:

Enter your name: _
Enter your age: _

Your name is <name> and your age is <age>.
Run Code Online (Sandbox Code Playgroud)

我一直试图弄清楚如何在Node中做这样的事情而不使用promptnpm模块.

我的尝试是:

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}`)
  })
})
Run Code Online (Sandbox Code Playgroud)

然而,这种嵌套的方式看起来很奇怪,无论如何我可以做到这一点,而不是像这样嵌套,以获得正确的顺序?

Pab*_*noz 16

zangw的答案就足够了,但我想我可以说清楚一点:

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)
Run Code Online (Sandbox Code Playgroud)

如果你不关心它,那么顺序问两个问题,你可以这样做:

//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)
Run Code Online (Sandbox Code Playgroud)