Reputation: 133
I am building a small CLI app using javascript, yargs, inquirer, and superagent. In inquirer I am asking the user to enter a choice of miles to be used in my app. I want to use that value somewhere else in my app but I can't seem to able to get the value returned. Below is my latest attempt. Any help into getting this value returned from selectRange
would be highly appreciated.
const selectRange = (result) => {
return inquirer.prompt([{
type: 'checkbox',
message: 'Select the range in miles to search',
name: 'miles',
choices: ['50', '100','150', '200', '250'] ,
validate: (result) => {
if (result.length > 1) {
return 'Error: You must select 1 choice only'
} else {
return true
}
},
filter: input => {
return input
}
}]).then(input => {
return input
})
}
const surroundingCitiesWeather = (location) => {
const range = selectRange()
console.log(`Range selected is ${range}`)
}
Here is a pic of my output, mind the last line
Upvotes: 0
Views: 2867
Reputation: 23
inquirer.prompt
returns a Promise, so in your case you just need to add async/await
to your function, and then just return answer.range
at the end.
Also, I don't think you need the result
function parameter. So the following should work:
const selectRange = async () => {
return await inquirer.prompt([
{
type: "checkbox",
message: "Select the range in miles to search",
name: "miles",
choices: ["50", "100", "150", "200", "250"],
validate: (result) => {
if (result.length > 1) {
return "Error: You must select 1 choice only";
}
return true;
},
filter: (input) => input,
},
]).then((answer) => answer.range);
};
Then the other block should also await for the promise to be resolved:
const surroundingCitiesWeather = async(location) => {
const range = await selectRange()
console.log(`Range selected is ${range}`)
}
Upvotes: 1
Reputation: 44609
Your function is returning a Promise, so you'd need to use it:
const surroundingCitiesWeather = (location) => {
selectRange().then(range => {
console.log(`Range selected is ${range}`)
})
}
If you use a recent version of node, you can make a bit clearer using async/await:
const surroundingCitiesWeather = async (location) => {
const { range } = await selectRange()
console.log(`Range selected is ${range}`)
}
Upvotes: 1