【问题标题】:readline.question doesn't run X times inside the loopreadline.question 不会在循环内运行 X 次
【发布时间】:2021-05-20 12:03:33
【问题描述】:

我在使用 Node.js 中的 readlinemodule 时遇到了一些问题。我需要与之前的问题响应一样多次询问客户 ID,但它只询问一次。

这是我当前的代码:

const readline = require('readline');
var prompts = {
    numEmails: null,
    customerIds: [],
    email: null,
    password: null
}

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

//Ask for new question
rl.question('Num Emails: ', (numEmails) => {
    for(let i = 0; i<numEmails; i++) {
        //Ask for new question
        rl.question('Id Customer' + i+1 + ': ', (customerId) => {
            prompts.customerIds.push(customerId)
        })
    }
});

当我运行脚本时,在回答我希望循环运行 4 次后,它应该要求 Id Customer 4 次,但它只执行一次:

我做错了什么?

【问题讨论】:

    标签: javascript node.js readline


    【解决方案1】:

    这是因为question 方法异步工作,因此您需要等待每个答案,然后再开始新的question。您可以通过以下方式处理。

    //Ask for new question
    rl.question('Num Emails: ', async (numEmails) => {
        for (let i = 0; i<numEmails; i++) {
            // Wait for a question to be answered. 
            await new Promise((resolve) => {
              rl.question('ID Customer ' + i+1 + ': ', (customerId) => {
                prompts.customerIds.push(customerId)
                
                resolve()
              }) 
            })
        }
    });
    

    我使用async/await 语法来处理promise,你可以在互联网上阅读更多关于它的信息。我的想法是我将 question 调用包装到 Promise 中,然后当我收到答案时,我会解决承诺,因此我们将提出下一个问题。

    【讨论】:

    • 谢谢,成功了!我已经尝试使用async/await,但是没有办法实现它。所以,我显然需要了解更多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2023-01-04
    相关资源
    最近更新 更多