Synchronous user input within an asynchronous function

I'm currently facing a challenge with implementing a synchronous user prompt in my electron app. Specifically, I have an object that contains a series of commands and template variables.

My objective is to substitute all unknown template variables with user input... synchronously. This means that the commands should only be executed after all variables have been replaced by user input.

Could you assist me with this issue?

Below is how I am initiating a sync user prompt (bootstrap model with a form) on my end (this test is functional and I receive the result synchronously once the user enters something in the prompt):

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

My dilemma lies in understanding the various async/await statements and how to integrate them into my standard replacement procedure. Here's my current progress:

const obj = {
    cmds: [
        'port {port}',
        'template1 {temp1} and template2 {temp2}',
        'template2 {temp2} and 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)

I neglected to mention that my main challenge is... the templatePrompt() function runs and the first prompt appears. However, before the user inputs any data, the entire process is already completed without replacing the template variables. :( My aim is to pause at each prompt until user input is provided.

Answer №1

This example demonstrates a way to simulate user input interaction through a series of prompts.

To achieve this functionality, an async function is used along with a for loop that awaits each response.

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(`Inquiring about "${question}"`)
        const response = await prompt()
        responses.push(response)
    }
    console.log(responses)
}

askUserQuestions(questions)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript popup cannot be shown at this time

I'm encountering an issue with displaying popups using JavaScript. Currently, only the div with class "popup" is being shown. When a user takes action, both popup and popup2 should be displayed but for some reason, it's not working as expected. ...

Is it possible to save a JavaScript interval in a jQuery element's data property?

In the process of developing a jQuery plugin, specifically a jQuery UI widget known as Smooth Div Scroll, I encountered an issue where I needed to store references to intervals that were unique to each instance of the plugin on a page. If I simply declared ...

Passing variable values from JavaScript to PHP without using a form: A guide

As a newcomer, I am facing a challenge in passing variable values from the client to a PHP server. While looking into this issue, I found multiple solutions related to sending form values. However, my goal is to transfer actual variable values rather than ...

Reasoning behind splitting this solution into a function utilizing Javascript

Today, while working on a coderbyte problem, I managed to solve it on my own without any outside help, and it felt fantastic. However, upon completion, I realized that I solved it without creating any functions. Rather, I kept referring back to a previous ...

How can I eliminate the need for 'library-preload.json' in my SAPUI5 application?

I am currently in the process of developing a SAPUI5 mobile application using cordova. The next step is to integrate another library, specifically cordova-plugin-file, into my project. However, I have encountered an issue where including this plugin causes ...

Is there a way to dim and deactivate a button after it has been clicked once?

Hello, I am attempting to disable and grey out a button after it has been clicked once in order to prevent the user from clicking it again until they refresh the page. I hope my question is clear enough and that you can understand me. Below is the HTML cod ...

Finding the index of a row using jQuery

I am encountering an issue with the following code: $("#myTable td").each(function(){ if($(this).html()=="") { rIndex1=$(this).parent().index(); //this value remains "1" rIndex2=$(this).rowIndex; //this value stays as "undefined" Un ...

Prevent Sending Blank Forms with Stripe js

Currently, I am working on a solution to prevent users from submitting the stripe form when certain inputs are left empty. To achieve this, I have integrated stripe.js elements into my form and implemented the form submission handling within my vue compone ...

Arranging a collection of objects (Displaying information in a random sequence)

Here is a summary of the data returned in a shortened version: var array = [{ "response": { "itineraries":[ { "price": { "totalPricePerPassenger":"104" ...

The method Object.keys.map does not return the initial keys as they were in the original object

I'm retrieving an object from my database and it looks like this: {availability: null bio: null category: "" createdAt: "2020-10-13T13:47:29.495Z" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

What is the best way to utilize .some() in determining if a specific property value is present within an array of objects?

I have an array filled with objects, each representing a individual heading to a movie theater. These objects include properties like Name, Age, and Hobby. If there is at least one person under 18 years old, the variable censor should be set to true. Desp ...

Issue with printing error messages for JavaScript form validation

I have implemented the following code for a form to handle validation and display errors below the fields when they occur: <!DOCTYPE html> <html> <head> <style type="text/css"> .errorcss { background-color: yellow; color:re ...

Why is Angular.orderBy not displaying any data on the Page?

Embarking on my first Angular project with Firebase Firestore, I am excited to showcase some of the code below. I recently learned Angular and here is what I have accomplished so far: Component.html <section class="rank"> <p class=& ...

Looping through items using v-model value in v-for

My website features a small form that allows users to submit new photos and view previously submitted photos. Users begin by selecting an album for the photo and then uploading it. Currently, I am encountering an issue in retrieving photos based on the sel ...

Tips for discreetly recording information without disrupting normal workflow until necessary

Every 100-200 uses, I encounter a strange bug that I just can't seem to reproduce consistently. It's not a top priority to fix, but I would like to address it. To investigate further, I would need to scatter about 30 console.log statements throu ...

Observing input value in Popover Template with Angular UI

I am currently working on a directive that utilizes the Angular Bootstrap Popover and includes an input field. Everything seems to be functioning properly, except for the fact that the watch function is not being triggered. For reference, you can view the ...

Upon attempting to add a new component, an error was encountered: Uncaught SyntaxError: Unexpected token export

I have created a React test project and added modules to my package.json as follows: { "name": "untitled", "version": "0.1.0", "private": true, "devDependencies": { "babel-preset-node5": "^12.0.1", "react-scripts": "0.9.5" }, "depe ...

Fill in the text box based on the selected option from the dropdown menu

My HTML code snippet is as follows: <select name="plot_no" id="plot_no" class="dropdown validate_B"> <option value="">Select number of Plots to book</option> <option value="1">1</option> <opti ...

Ensure to include Express validator version 6.4.0 in conjunction with express upload to verify the input data before proceeding with a POST request on the specified

Currently, I am facing a challenge in validating inputs, including an image upload, using express-validator and express-upload to parse multipart data. My goal is to validate the file being uploaded as an image or allow for no image upload. Despite followi ...

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...