utils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict';
  2. var _ = require('lodash');
  3. var rx = require('rx-lite');
  4. var runAsync = require('run-async');
  5. /**
  6. * Create an oversable returning the result of a function runned in sync or async mode.
  7. * @param {Function} func Function to run
  8. * @return {rx.Observable} Observable emitting when value is known
  9. */
  10. exports.createObservableFromAsync = function (func) {
  11. return rx.Observable.defer(function () {
  12. return rx.Observable.create(function (obs) {
  13. runAsync(func, function (value) {
  14. obs.onNext(value);
  15. obs.onCompleted();
  16. });
  17. });
  18. });
  19. };
  20. /**
  21. * Resolve a question property value if it is passed as a function.
  22. * This method will overwrite the property on the question object with the received value.
  23. * @param {Object} question - Question object
  24. * @param {String} prop - Property to fetch name
  25. * @param {Object} answers - Answers object
  26. * @...rest {Mixed} rest - Arguments to pass to `func`
  27. * @return {rx.Obsersable} - Observable emitting once value is known
  28. */
  29. exports.fetchAsyncQuestionProperty = function (question, prop, answers) {
  30. if (!_.isFunction(question[prop])) {
  31. return rx.Observable.return(question);
  32. }
  33. return exports.createObservableFromAsync(function () {
  34. var done = this.async();
  35. runAsync(question[prop], function (value) {
  36. question[prop] = value;
  37. done(question);
  38. }, answers);
  39. });
  40. };