【问题标题】:Getting information from one function and using it in another从一个函数中获取信息并在另一个函数中使用它
【发布时间】:2021-06-12 22:02:22
【问题描述】:

前几天我为我一直在从事的一个项目做了一些研究,它把我带到了这个地方。这将完美地满足我的需求,但我无法弄清楚如何在“question1”函数中获取收集到的答案并能够在“main”函数中使用该数据。有人可以给我这样的建议吗?

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

const question1 = () => {
    return new Promise((resolve, reject) => {
        rl.question('q1 What do you think of Node.js? ', (answer) => {
            resolve()
        })
    })
}

const question2 = () => {
    return new Promise((resolve, reject) => {
        rl.question('q2 What do you think of Node.js? ', (answer) => {
            resolve()
        })
    })
}

const main = async () => {
    await question1()
    await question2()
    rl.close()
}

main()

【问题讨论】:

  • 将答案传递给resolve (resolve(answer)),然后在main 中您可以执行const answer = await question1()
  • 成功了,谢谢!

标签: javascript readline


【解决方案1】:

正如@Nick 在评论中提到的那样,将answer 传递给Promise 提供的resolve() 方法,就像这样

const question = () => {
  return new Promise((resolve, reject) => {
    rl.question("q2 What do you think of Node.js? ", (answer) => {
      resolve(answer);
    });
  });
};

const main = async () => {
  const answer = await question();
};

现在您应该可以在 main 中访问答案了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2012-12-23
    • 2016-10-20
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    相关资源
    最近更新 更多