Question: how to use prompt with code running between confirm to continue
trevordmiller opened this issue · 3 comments
trevordmiller commented
All the documentation and examples show prompt being used to gather all input upfront before running code. But how can I use prompt a few times while running code without having callback hell? Some pseudocode for example:
// run some code
// Prompt for “Does this look right? Enter “yes” to continue
// Once “yes” is entered, run some more code
// Prompt for “Does this look right? Enter “yes” to continue.
etc.
trevordmiller commented
It seems that nested callbacks are how this has to be done right now based on the examples/
- like this:
prompt.start();
// do stuff here
const property1 = {
name: 'yes',
message: 'are you sure (1)?',
validator: /yes/,
warning: 'Must respond yes to continue',
default: ''
};
prompt.get(property1, () => {
// do more stuff here after "yes" from user
const property2 = {
name: 'yes',
message: 'are you sure (2)?',
validator: /yes/,
warning: 'Must respond yes to continue',
default: ''
};
prompt.get(property2, () => {
// do even more stuff here after "yes" from user
const property3 = {
name: 'yes',
message: 'are you sure (3)?',
validator: /yes/,
warning: 'Must respond yes to continue',
default: ''
};
prompt.get(property3, () => {
// do yet more stuff here after "yes" from user
etc.
}
}
});
Is there a way to condense this into a flat synchronous / procedural style from top to bottom? Perhaps with async/await?
trevordmiller commented
Figured it out:
const prompt = require('prompt')
prompt.start()
userInput = property =>
new Promise(resolve => {
prompt.get(property, (err, result) => {
if (err) {
reject(err)
}
resolve(result)
})
})
const main = async () => {
try {
console.log('Starting...')
const result1 = await userInput({
name: 'confirmThing1',
message: 'Does this look good to continue?',
validator: /yes/,
warning: 'Must respond yes to continue',
default: '',
})
console.log('result1', result1)
const result2 = await userInput({
name: 'confirmThing2',
message: 'Does this look good to continue?',
validator: /yes/,
warning: 'Must respond yes to continue',
default: '',
})
console.log('result2', result2)
console.log('Wrapping up...')
} catch (error) {
console.error(error)
}
}
main()
trevordmiller commented
Submitted to examples/
: #191