具有同步用户提示的异步功能

Async function with sync user prompt

我正在尝试让我的 Electron 应用程序中的同步用户提示正常工作。 更准确地说,我有一个包含一组命令和模板变量的对象。

我想用用户输入...同步替换所有未知的模板变量。这样命令只在我的所有变量都被替换后才发送。

你能帮帮我吗?

这就是我如何在我这边调用同步用户提示(bootstrap 带有表单的模式)(此测试有效,在用户将内容放入提示):

async function test(gui) {
    const result = await gui.syncPrompt('User question')
    console.log('result:', result)
}
test(this.gui)

我的问题是,我对所有 async/await 语句感到非常困惑,我不知道如何将其包含在我的正常替换过程中? 到目前为止我得到了什么:

const obj = {
    cmds: [
        'port {port}',
        'template1 {temp1} und template2 {temp2}',
        'template2 {temp2} und template1 {temp1}'
    ]
}

const templatePrompt = async () => {
    const map = {}
    await obj.cmds.forEach(async (element, index, array) => {
        const patt = /{.*?}/gmi
        patt.lastIndex = 0
        if (patt.test(element)) {
            await obj.cmds[index].match(patt).map(async (value) => {
                let userInput = map[value]
                if (!userInput) {
                    // Create Prompt here.
                    // userInput = Math.random() * 10
                    userInput = await this.gui.syncPrompt('User question:')
                }
                map[value] = userInput
                return true
            })
            await Object.keys(map).map(async (key) => {
                obj.cmds[index] = obj.cmds[index].replace(key, map[key])
                return true
            })
        }
    })
}
await templatePrompt()
console.log(obj)

我忘了说我真正的问题是...函数 templatePrompt() 是 运行,我的第一个提示出现了。与此同时,在用户甚至键入一些输入之前,打孔过程已经完成,而无需替换模板变量。 :( 我的目标是在每次提示时都达到 "pause"。

以下代码模拟等待用户从一系列提示中输入。

只需使用一个 async 函数、一个 for 循环和 await 每个响应。

const random = (arr) => arr[~~(Math.random()*arr.length)]

const simulatedNamePrompt = () => 
    new Promise((resolve) => 
        setTimeout(() => resolve(random(['Ben', 'Sam', 'John'])), 1500))

const simulatedAgePrompt = () => 
    new Promise((resolve) => 
        setTimeout(() => resolve(random(['19', '20', '21'])), 1500))

const questions = [
    {
        question: 'What is your name?',
        prompt: simulatedNamePrompt
    },
    {
        question: 'What is your age?',
        prompt: simulatedAgePrompt
    }
]

async function askUserQuestions(questions) {
    const responses = []
    for(const { question, prompt } of questions) {
        console.log(`Asking "${question}"`)
        const response = await prompt()
        responses.push(response)
    }
    console.log(responses)
}

askUserQuestions(questions)