0

OK, so I have been working on a console input system for a project workflow and user input. I am getting frustrated as there seems to be no actual answer to this simple problem. Currently I wrote simple modules to handle user input but the problem is when I throw a check answer, it executes them parallel to my read input. Here is the module that prompts a bool question:

exports.bool = function(question){
ret = null;
answer = ['y','n']
inquery.question(`> ${question} [${answer}] `, (out) => {
    ret = out;  
    inquery.close();
});
if (ret == 'y')
    return true;
else
    return false;
}

And then here is the part I'm asking for how do they want to setup:

async function main(){
    themes = rw.listFiles('./gp-content/gp-themes');
    config = './gp-config.json';
    
    answer = await inquery.bool('Setup new environment?');
    console.log(answer);
    if (answer)
        initiate();
    else
        buildPages();
}

& when I execute I expect:

Setup new environment? [y,n] y true

But I get:

Setup new environment? [y,n] false y

I'm sorry if this is a repeated question but there wasn't a straight answer for this problem. So I appreciate any new methods or feedback in understanding Async better. Also I am trying to avoid using timeout as it seems to be obsolete.

  • 1
    `exports.bool` needs to be `async` or return a Promise if you want to `await` it. – Barmar Aug 25 '20 at 20:37
  • I've tried that. Does the same thing. It continues with the console.log(answer) part. – Info zDesignz Aug 25 '20 at 20:41
  • 2
    Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Klaycon Aug 25 '20 at 20:44
  • You're make a decision based on the value of `ret` before it is set in the callback given to `question`. – Heretic Monkey Aug 25 '20 at 20:47
  • @Klaycon thanks, this article makes sense, but there should be a way to avoid callback functions. I now realize that the answer is waiting for inquery.bool to execute but at the mean time it'd get a false value as its not executed. But is there a way to not use call backs? – Info zDesignz Aug 25 '20 at 20:54
  • @InfozDesignz No. That would require the runtime to sit there and block all other code from executing while it waits for the one network call or whatever else to resolve. You can, however, *promisify* the callback API and then write code using `async/await` - which reads just like synchronous code, though it indeed still uses callbacks in the backend. – Klaycon Aug 25 '20 at 20:57
  • @Klaycon awesome I will look into it. Thank you. I'll update you here if something comes up :-D – Info zDesignz Aug 25 '20 at 21:25

0 Answers0