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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/js/150375.html

猜你在找的JavaScript相关文章