javascript - 如何在执行期间使用 rxjs 向 Inquirer JS 动态添加问题?

标签 javascript rxjs inquirer inquirerjs

我想向用户提问,而不是立即排好所有问题。

文档中提到了 rxjs,但我觉得文档中关于如何在执行提示时正确添加问题方面存在差距,或者至少它对我来说不太适用。

https://www.npmjs.com/package/inquirer#reactive-interface

Internally, Inquirer uses the JS reactive extension to handle events and async flows.

This mean you can take advantage of this feature to provide more advanced flows. For example, you can dynamically add questions to be asked:


var prompts = new Rx.Subject();
inquirer.prompt(prompts);

// At some point in the future, push new questions
prompts.next({
  /* question... */
});
prompts.next({
  /* question... */
});

// When you're done
prompts.complete();

And using the return value process property, you can access more fine grained callbacks:


inquirer.prompt(prompts).ui.process.subscribe(onEachAnswer, onError, onComplete);

最佳答案

所以感谢 this blog post by jana e. beck 的一些启发,我制作了我需要的代码。来自 jana 的示例和提示有点过时了,由于某种原因,使用 rxjs 中的 Subject 不再起作用,至少它对我不起作用。然而,通过将发射器存储在观察者创建回调之外,这很容易解决。请记住将 rxjs 作为依赖项添加到您的项目中(与 InquirerJS 当前使用的相同,可能会有所帮助)。

const inquirer = require("inquirer");
var { Observable } = require("rxjs");

let emitter;

var prompts = Observable.create(function(e) {
  emitter = e;
  // need to start with at least one question here
  emitter.next({
    type: "list",
    name: "fruits",
    message: "What is your favorite fruit?",
    choices: [
      {
        name: "Banana"
      },
      {
        name: "Apple"
      },
      {
        name: "Pear"
      }
    ]
  });
});

let times = 0;

inquirer.prompt(prompts).ui.process.subscribe(
  q => {
    let dots = new Array(times).fill(".").join("");

    if (q.answer.toLowerCase() === "pear") {
      console.log("That's Great. I would never forget a Pear-eater.");
      emitter.complete();
    }

    emitter.next({
      type: "list",
      name: "fruits",
      message:
        "Sorry, what is your favorite fruit? I forgot, was it " +
        q.answer +
        ", or something else?",
      choices: [
        {
          name: "Uh, Banana.." + dots,
          value: "banana"
        },
        {
          name: "Uh, Apple.." + dots,
          value: "apple"
        },
        {
          name: "Pear!",
          value: "pear"
        }
      ]
    });

    times++;
  },
  error => {
    console.log("Hm, an error happened. Why?");
  },
  complete => {
    console.log("I think we are done now.");
  }
);

这个提示以及博客文章应该是您开始所需的内容。请记住,如果您愿意,您可以一次将多个问题排成队列。

完成后,输入 emitter.complete();某处结束提示。

关于javascript - 如何在执行期间使用 rxjs 向 Inquirer JS 动态添加问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078788/

相关文章:

javascript - javascript RegExp 正则表达式错误中的 Internet Explorer 11 语法错误

typescript - RxJS 在回调中合并 Observable

javascript - RxJS - 我需要退订吗

javascript - 当用户向下滚动窗口 JAVASCRIPT 时,将 div 的颜色淡化为不透明

javascript - 获取 xmlDocument 对象

javascript - 模拟点击DIV

angular - rxjs:Observable.pipe 不是函数

node.js - 使用 Jest 进行单元测试 Inquirer

javascript - 如何清除 Inquirer.js 中的错误输入