2016-11-08 26 views
1

我有我的發電機代碼如下。當我運行它時,我看到一些有趣的行爲。一旦它詢問第二個Add property...,它的呼叫代碼writing。一旦提示完成,不應該運行?我究竟做錯了什麼?yeoman發電機提示和運行循環

app/index.js

'use strict' 
var generators = require('yeoman-generator'); 
var questions = require('./questions'); 

module.exports = generators.Base.extend({ 
    constructor: function() { 
     generators.Base.apply(this, arguments); 
     this.argument('name', { type: String, required: true }); 
    }, 

    initializing: function() { 
     this.properties = []; 
    }, 
    prompting: { 
    askForProperties: questions.askForProperties 
    }, 
    writing: function(){ 
    this.log("brewing your domain project"); 
    } 
}); 

app/questions.js

'use strict' 

var chalk = require('chalk'); 

function askForProperties() { 
    var prompts = [ 
    { 
     type: 'confirm', 
     name: 'addProp', 
     message: 'Add property to your model (just hit enter for YES)?', 
     default: true 
    }, 
    { 
     type: 'input', 
     name: 'propName', 
     message: 'Give name to your property?', 
     when: function (response) { 
      return response.addProp; 

     } 
    }, 
    { 
     type: 'list', 
     name: 'propType', 
     message: 'Pick a type for your property', 
     choices: [ 
      { 
       value: 'string', 
       name: 'string', 
      }, 
      { 
       value: 'int', 
       name: 'int' 
      }, 
      { 
       value: 'bool', 
       name: 'bool' 
      }, 
      { 
       value: 'decimal', 
       name: 'decimal' 
      }], 
     default: 0, 
     when: function (response) { 
      return response.addProp; 

     } 
    } 
]; 

return this.prompt(prompts).then(function (answers) { 
    var property = { 
     propertyName: answers.propName, 
     propertyType: answers.propType 
    }; 

    this.properties.push(answers.propName); 

    if (answers.addProp) { 
     askForProperties.call(this); 
    } 
}.bind(this)); 
} 

module.exports = { 
    askForProperties 
}; 

回答

0

看起來你正在爭奪自耕農對象語法。你不是承諾返回提示方法

對於任何人尋找到這一點,是在章節的Yeoman docs Running Context(您正在使用askForProperties方法返回一個承諾返回一個對象)的題異步任務

prompting() { 
    const done = this.async(); 
    this.prompt(prompts).then((answers) => { 
     this.log('My work after prompting'); 
     done(); 
    }); 
} 

這允許系統知道您的承諾何時已經返回並因此知道要等待執行下一個優先級步驟。

但是,您真正想要做的是從prompting()方法本身返回承諾。

prompting() { 
    const promise = this.prompt(prompts).then((answers) => { 
     this.log('Handling responses to prompts'); 
    }); 
    return promise; 
} 

在特定情況下,你已經設置的諾言正確,但是你是不是將其返回到提示屬性(只是到askForProperties屬性)。

由於askForProperties已經回國的承諾,你的解決將是:

prompting: questions.askForProperties