【发布时间】:2020-03-18 08:16:00
【问题描述】:
我正在尝试在我的电子应用程序中获得同步用户提示以正常工作。 更准确地说,我有一个带有一组命令和模板变量的对象。
我想用用户输入替换所有未知的模板变量...同步。这样命令只有在我的所有变量都被替换后才会发送。
你能帮帮我吗?
这就是我如何在我这边调用同步用户提示(带有表单的引导模式)(此测试正在运行,并且在用户在提示中输入内容后我同步收到 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() 正在运行并且我的第一个提示出现了。同时,在用户输入一些输入之前,打孔过程已经完成,无需替换模板变量。 :( 我的目标是在每次提示时实现“暂停”。
【问题讨论】:
-
您的代码是否存在特定问题? (除了你很困惑)
-
async/await并不神奇,它只是承诺的语法糖。我认为你应该使用 Promise,当你完全理解它们时,你可以使用 async/await 来压缩你的代码。例如,通过这种方式,您会注意到等待forEach是没有意义的,因为这就像在 forEach 结果上调用then。 -
感谢您的帮助。 :) 我忘了提到我真正的问题是...函数
templatePrompt()正在运行并且我的第一个提示出现了。同时,在用户输入一些输入之前,空洞过程已经完成,无需替换模板变量。 :( 我的目标是在每次提示时实现“暂停”。
标签: javascript async-await electron prompt synchronized