微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 这个例子可以使用promises吗?

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

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

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

我的尝试是:

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}`)
  })
})

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

解决方法

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)

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

//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)

原文地址:https://www.jb51.cc/js/150375.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐