node.js - Using Q to create an async user input sequence -
i toying q , promptly , trying ask, in sequence, user input stuff. example :
what name? bob age? 40 hello bob (40)!
(yes! it's simple "hello world!" program.)
and here code trying, directly q's github project page :
q.fcall(promptly.prompt, "what name? ") .then(promptly.prompt, "what age? ") .done(function(name, age) { console.log("hello " + name + " (" + age + ")"); });
});
but not working expected (maybe i'm reading wrong?). whatever try, seems promptly.prompt
listening keystroke in parallel, , .done
function called right away, resulting
/path/to/node_modules/promptly/index.js:80 fn(null, data); ^ typeerror: undefined not function @ /path/to/node_modules/promptly/index.js:80:9 ...
once hit enter. idea why doing , how can accomplish i'm trying do?
** edit **
basically, end goal create reusable function invoked :
promptall({ 'name': "what name? ", 'age': "what age? " }).done(function(input) { console.log(input); // ex: { name: "bob", age: 40 } });
** update **
here's working solution, had use nfcall
suggested wiredpraine :
function multiprompt(args) { function _next() { if (keys.length) { var key = keys.pop(); q.nfcall(promptly.prompt, args[key]).done(function(value) { result[key] = value; _next(); }); } else { def.resolve(result); } }; var def = q.defer(); var keys = _.keys(args).reverse(); var result = {}; _next(); return def.promise; };
(note : using underscore, same can achieved standard object iterator.)
below 2 approaches.
first, you'd need use nfcall
q uses nodejs conventions callbacks.
but, functions aren't promises, you'll need handle chaining , synchronous behavior differently.
in first example, start1
, code creates instance of defer
, returns promise. when prompt
function returns, resolve
s deferred object instance , passes value
of function (ideally prompt). should handle errors, etc. in "real" code.
in both examples, i've added function grab result of the promise resolving. it's not passed parameters last done
instance. function passed done
execute first promise resolved (after prompt
has returned in case).
var promptly = require('promptly'); var q = require('q'); // make simple deferred/promise out of prompt function var prompter = function(text) { var deferred = q.defer(); promptly.prompt(text, function(err, value) { deferred.resolve(value); }); return deferred.promise; }; // option uses promise option prompt name. function start1() { prompter("what name?").then(function(name) { prompter("your age?").then(function(age) { console.log("hello " + name + " (" + age + ")"); }); }); } // 1 uses nfcall funcitonality directly call // promptly.prompt function (and waits callback). function start2() { q.nfcall(promptly.prompt, "what name? ") .then(function(name) { q.nfcall(promptly.prompt, "what age? ") .done(function(age) { console.log("hello " + name + " (" + age + ")"); }); }); } //start1();
Comments
Post a Comment