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

问题描述 投票:0回答:1

我正在尝试在我的电子应用程序中获取同步用户提示,以使其正常工作。更确切地说,我有一个带有一组命令和模板变量的对象。

我想用用户输入...替换所有未知的模板变量...。因此,仅在替换所有变量后才发送命令。

您能帮我吗?

这就是我在一边调用同步用户提示(带有表单的引导程序模式)(此测试有效,并且用户在提示中放入内容后,我同步收到result:]

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

我的问题是,我对所有异步/等待语句都感到非常困惑,我不知道如何在正常替换过程中添加它?我到目前为止所得到的:

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()正在运行,并且出现了我的第一条提示。同时,即使用户输入了一些输入,打孔过程也已经完成,而无需替换模板变量。 :(我的目标是在每个提示上都达到“暂停”。

javascript async-await electron prompt synchronized
1个回答
1
投票

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

仅使用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)
© www.soinside.com 2019 - 2024. All rights reserved.