【问题标题】:How to do a recursive prompt in Yeoman with promises?如何在 Yeoman 中使用 promise 进行递归提示?
【发布时间】:2017-06-04 23:12:56
【问题描述】:

我试图弄清楚如何使用 promises 使用 yeoman 生成器进行递归提示。我正在尝试生成一个表单生成器,它将首先询问表单组件的名称,然后为每个输入(即:名字、姓氏、用户名等)询问一个名称(将用作 id)。我已经使用回调找到了这个问题的答案,但我想坚持承诺。下面是我到目前为止的代码以及我试图为递归做的但没有工作的代码。任何帮助和建议都非常感谢您提前谢谢!

const Generator = require('yeoman-generator')

const questions = [
  { type: 'input',
    name: 'name',
    message: 'What is the name of this form?',
    default: 'someForm'
  },
  {
    type: 'input',
    name: 'input',
    message: 'What is the name of the input?'
  },
  {
    type: 'confirm',
    name: 'askAgain',
    message: 'Is there another input to add?'
  }

]

module.exports = class extends Generator {


  prompting() {
    return this.prompt(questions).then((answers) => {
      if (answers.askAgain) {
        this.prompting()
      }
       this.userOptions = answers
       this.log(this.userOptions)
    })
  }

}

【问题讨论】:

    标签: javascript recursion yeoman yeoman-generator


    【解决方案1】:

    对于任何偶然发现这篇文章并寻找答案的人来说,这就是我最终要让它发挥作用的方法。正如您在扩展 Generator 的 Form 类中看到的那样,我在其中有一个名为 prompting() 的方法。这是 Yeoman 的循环将其识别为优先级的方法,并且在返回某些内容之前不会离开此方法。由于我正在返回一个承诺,它会等到我的承诺完成后再继续。对于我的第一个提示,这正是我需要的,但是对于第二个提示,您可以添加

    const done = this.async()
    

    在您的方法开始时。这告诉 yeoman,您将发生一些异步代码,并且在执行完成之前不要越过包含此代码的方法。如果你不使用它并且在你的类中有另一个优先级方法,例如当你准备好生成生成的代码时,yeoman 将跳过你的方法,而不等待你的异步代码完成。您可以在我的方法 prompting2() 中看到,只要用户声明有另一个名称输入,我就会递归调用它,并且它将继续这样做,直到他们说没有另一个名称输入。我确信有更好的方法可以做到这一点,但这种方式对我来说非常有用。我希望这可以帮助任何正在寻找方法的人!

    const Generator = require('yeoman-generator')
    
    const questions = [
        { type: 'input',
          name: 'name',
          message: 'What is the name of this form?',
          default: 'someForm'
        }
    ]
    
    const names = [
     {
       type: 'input',
       name: 'inputs',
       message: 'What is the name of the input?',
       default: '.input'
     },
     {
       type: 'confirm',
       name: 'another',
       message: "Is there another input?",
       default: true
     }
    ]
    
    const inputs = []
    
    class Form extends Generator {
    
      prompting() {
        return this.prompt(questions).then((answers) => {
          this.formName = answers.name
          this.log(this.formName)
       })
      }
    
      prompting2 () {
         const done = this.async()
         return this.prompt(names).then((answers) => {
          inputs.push(answers.inputs)
          if (answers.another) this.prompting2()
          else {
           this.inputs = inputs
           this.log(this.inputs)
           done()
          }
        })
      }
    
    }
    
    module.exports = Form
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 2019-05-16
    • 2018-06-10
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多