从一个函数获取信息并在另一个函数中使用它

Getting information from one function and using it in another

前几天我为我一直在做的一个项目做了一些研究,它让我想到了这个。这将完美地满足我的需求,但我无法弄清楚如何在比方说“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()

正如@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();
};

现在您应该可以在主目录中访问答案了