这个例子可以使用promises吗?

时间:2016-01-16 00:56:38

标签: javascript node.js

我基本上是在尝试编写一个非常基本的程序,它的工作原理如下:

Enter your name: _
Enter your age: _

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

我一直试图在不使用prompt npm模块的情况下弄清楚如何在Node中做这样的事情。

我的尝试是:

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

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

3 个答案:

答案 0 :(得分:13)

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)

答案 1 :(得分:2)

以下是Q

的一个示例
var readline = require('readline');
var Q = require('q');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var q1 = function () {
    var defer = Q.defer();
    rl.question('What is your name? ', (name) => {
        defer.resolve(name);
    }); 

    return defer.promise;
};

q1().then(function(name) {
    rl.question('What is your age? ', (age) => {
        console.log(`Your name is ${name} and your age is ${age}`)
    });
});

或使用简单的Promise

function question1() {
    return new Promise(function(resolve) {
        rl.question('What is your name? ', (name) => {
            resolve(name);
        });         
    });

};

question1().then(function(name) {
    rl.question('What is your age? ', (age) => {
        console.log(`Your name is ${name} and your age is ${age}`)
    });    
});

答案 2 :(得分:-4)

没有承诺就有办法做到这一点。

rl.question('What is your name? ', getUserName);

function getUserName (name) {
    rl.question('What is your age? ', getUserAge(name));  
}

function getUserAge (name) {
    return function (age) {
        console.log(`Your name is ${name} and your age is ${age}`)
    }
}

请参阅,没有嵌套但正确重构的函数。您可以而且应该对返回承诺的api做同样的事情。匿名函数是该语言的一个很好的功能,但这并不意味着你必须将它用于所有内容。