具有同步功能的异步功能

时间:2020-03-18 08:16:00

标签: javascript async-await electron prompt synchronized

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

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

你能帮我吗?

这是我如何在自己的侧面上调用同步用户提示(带有表单的引导程序模式)(此测试有效,并且在用户在提示中放入内容后,我同步收到result):

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

1 个答案:

答案 0 :(得分: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)