我正在创建一个运行正常的 yeoman 生成器,现在我需要添加一个列表
从异步(我希望它在后台运行)调用可能需要大约 2-3 秒来检索数据,所以我把它放在 initializing
因为用户将把这个问题作为第三个问题。 (见下面的对象)
所以当用户点击问题3时,数据检索过程将开始避免等待。基本上我希望数据检索将在后台进程中完成..
我的问题是:
initialize
中运行异步方法我尝试的是以下内容:
export default class AppGenerator extends Generator {
private listData: ListInstance[];
async initializing() {
this.props = {
appName: "app",
apiName: "app-api",
};
//--------------Here I call to async function --------------//
this.listData = await GetInstances();
}
async prompting() {
const answers = await this.prompt([
{
name: "appName",
message: "Project name: ",
type: "input",
default: this.props.appName,
},
{
name: "apiName",
message: "API name: ",
type: "input",
default: this.props.apiName,
},
{
name: "instanceName",
type: "list",
message: "Choose instance",
choices: this.listData,
},
];
}
writing() {
//here I dont get the `this.answers` , I need to get the values from the answers
}
最佳答案
首先是一些观察:
另外,请确保您的答案可以在 Prompting 方法之外访问(即使用
this
作为类 - 用于示例)...
async prompting() {
var prompts = new Rx.Subject();
this.prompt(prompts);
prompts.next({
name: "appName",
message: "Project name: ",
type: "input",
default: this.props.appName,
});
prompts.next({
name: "apiName",
message: "API name: ",
type: "input",
default: this.props.apiName,
});
this.listData = await GetInstances();
prompts.next({
name: "instanceName",
type: "list",
message: "Choose instance",
choices: this.listData,
});
prompts.complete();
this.answers = this.prompt(prompts).ui.process.subscribe(onEachAnswer, onError, onComplete);
}
...
Other notes: The use of
await
will start the call toGetInstances
when thePrompting
section is started. However, it will not allow the final question to be asked untilGetInstances
has returned.
1: Yeoman uses Inquirer.js
2: Reactive Prompting in Inquirer.js
关于javascript - Yeoman 生成器运行异步最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61239018/