2017-06-02 10 views
3

私は、約束を使ってヨーヨンジェネレータで再帰的なプロンプトを行う方法を理解しようとしています。私はフォームコンポーネントの名前を最初に尋ねるフォームジェネレータを生成しようとしています。そして、各入力(つまり:firstName、lastName、usernameなど)の名前(idとして使用されます)を求めます。私はコールバックを使用してこの質問の答えを見つけましたが、私は約束に固執したいと思います。以下は私がこれまでに持っていたコードであり、再帰のために何をしようとしているのですが、動作していません。どんな助けやアドバイスもありがとうございます。約束でYeomanで再帰的なプロンプトを実行するには?

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) 
    }) 
    } 

} 

答えて

1

回答を探しているこのポストを見つけた人にとって、これは私がそれを機能させるためにやったことです。 Generatorを拡張したFormクラスでわかるように、そこにはprompting()というメソッドがあります。これは、Yeomanのループが優先順位として認識するメソッドであり、何かが返されるまでこのメソッドを終了しません。私は約束を返すので、私の約束が終わるまで待つことになる。私の最初のプロンプトのために私が必要とするものですが、プロンプト2で2番目のプロンプトが表示されるようにするには、メソッドの開始時に

を追加することができます。これは、あなたがいくつかの非同期コードを実行し、doneが実行されるまでこれを含むメソッドを移動しないようにすることを、yeomanに伝えます。これを使用せずに、生成されたコードを生成する準備ができているときのwrite()のように、クラスの後ろに別の優先メソッドを持っていれば、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 
+0

「this.async」は必ずしも必要ではありません。代わりに 'return this.prompting2()'を返すことで、チェーンの約定を解決することができます。これはYeoman特有のものではありませんが、これがPromiseの働きです。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise –

+0

説明をありがとうございます!私は私の答えを編集する – pbie42

関連する問題