Home > Software design >  How can I prompts loop in node js?
How can I prompts loop in node js?

Time:03-27

I want the main.js loop to be re-selectable when the user has selected option.

here the code

main.js

const prompts = require('prompts');
var option = require('./option.js');

(async () => {
  const response = await prompts({

    type: 'select',
    name: 'value',
    message: 'choice',
    
    choices: [
      { title: 'option1', description: 'option1 description', value: '1' },
     
      { title: 'exit',  description: 'exit from script',value: '0' }

    ],
    initial: 1

    
  }
  
  
  
  ).then(response => {


if(response.value == 1){


  console.info('you select option1');
option.option1()

// i want to run main.js again here
}
else {
  console.info('you select exit');
// i want to exit from main.js 
}
  });

})();

option.js

module.exports = {


    option1:function() {
        console.log("You have selected option 1")
    }
}

When the user has selected option1, after the option.js script's function is done, I would like it to return to the new options page.

I've tried many ways but I still can't find a way. I don't know what I should do, I have been stuck with this problem for hours.

CodePudding user response:

Is this the solution to your problem? Also notice when using await, dont use then.

const prompts = require('prompts');
var option = require('./option.js');


async function prompt () {
 
  const response = await prompts({

    type: 'select',
    name: 'value',
    message: 'choice',
    
    choices: [
      { title: 'option1', description: 'option1 description', value: '1' },
     
      { title: 'exit',  description: 'exit from script',value: '0' }

    ],
    initial: 1
  })
  
  return response.value === '1'?option.option1() & prompt():false
}
prompt()
  • Related