简体   繁体   中英

How can I use more than one inquirer at once for JavaScript

inquirer 
    .prompt([
        {
            name: 'name',
            message: 'Enter team members name.',
        },
        {
            name: 'role',
            type: 'list',
            message: 'Enter a team members role',
            choices: [
                'Engineer',
                'Manager',
                'Intern'
            ],
        },
        {
            name: 'id',
            message: 'Please enter team members id',
            type: 'input'
        },
        {
            name: 'email',
            message: 'Please enter team members email'
        }

    ])
    .then(function(data){
        let moreRole = '';

        if (data.role === 'Engineer') {
            moreRole = 'Github username.'
        }else if(data.role === 'Intern') {
            moreRole = 'school name.'
        }else {
            moreRole = 'office Number.'
        }        
    })


    inquirer
        .prompt([
            {
                message: `Enter team members ${moreRole}`,
                name: 'moreRole'
            },
            {
                type: 'list',
                message: 'Would you like to add another team member?',
                choices: [
                    'Yes',
                    'No'
                ],
                name: 'anotherMember'
            }
        ])
        .then(moredata => {
            console.log(moredata)
        });

So the first inquirer works but when I add the second one and run it. It doesn't work properly. Can I not use two inquirers back to back? How would I get it to work. In the console it just asks me the first question and and goes back out and doesn't let me answer it.

The API of the package is based on Promises. The first inquirer.prompt call fires the first prompt, but since you are using the then way of handling resolved Promises, it is not waiting for the operation to complete, it just goes through to the second inquirer.prompt call.

To bypass this, you could wrap your code into an async function and prepend await to each inquirer.prompt (or at least to all but the last one).

Should look something like this:

async function callInquirers() {
    const inq1 = await inquirer.prompt([...]);
    const inq2 = await inquirer.prompt([...]);

    // do stuff with results inq1 and inq2
}

Check docs for Promises, event loop, async/await if you want more insight on this matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM