Skip to content

Commit

Permalink
Merge pull request #196 from caub/promisify
Browse files Browse the repository at this point in the history
promisify prompt.get
  • Loading branch information
gangstead committed Mar 5, 2020
2 parents 0ff93b6 + 33ddf56 commit 8d5495c
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
4 changes: 3 additions & 1 deletion .gitignore
@@ -1,3 +1,5 @@
node_modules/
node_modules/*
npm-debug.log
npm-debug.log

package-lock.json
6 changes: 6 additions & 0 deletions README.md
Expand Up @@ -46,6 +46,12 @@ This will result in the following command-line output:
email: some-user@some-place.org
```

If no callback is passed to `prompt.get(schema)`, then it returns a `Promise`, so you can also write:
```js
const {username, email} = await prompt.get(['username', 'email']);
```


### Prompting with Validation, Default Values, and More (Complex Properties)
In addition to prompting the user with simple string prompts, there is a robust API for getting and validating complex information from a command-line prompt. Here's a quick sample:

Expand Down
10 changes: 10 additions & 0 deletions lib/prompt.js
Expand Up @@ -192,6 +192,16 @@ prompt.history = function (search) {
// Gets input from the user via stdin for the specified message(s) `msg`.
//
prompt.get = function (schema, callback) {
if (typeof callback === 'function') return prompt._get(schema, callback);

return new Promise(function (resolve, reject) {
prompt._get(schema, function (err, result) {
return err ? reject(err) : resolve(result);
});
});
};

prompt._get = function (schema, callback) {
//
// Transforms a full JSON-schema into an array describing path and sub-schemas.
// Used for iteration purposes.
Expand Down
20 changes: 20 additions & 0 deletions test/prompt-test.js
Expand Up @@ -12,6 +12,10 @@ var assert = require('assert'),
macros = require('./macros'),
schema = helpers.schema;

// fix for vows, util.print/puts was removed from node
require('util').print = console.log;
require('util').puts = console.log;

// A helper to pass fragments of our schema into prompt as full schemas.
function grab () {
var names = [].slice.call(arguments),
Expand Down Expand Up @@ -751,6 +755,22 @@ vows.describe('prompt').addBatch({
}
}
}
}).addBatch({
"when using prompt": {
"the get() method also works as a Promise": {
topic: function () {
var that = this;

prompt.override = { xyz: 468, abc: 123 };
prompt.get(['xyz', 'abc'])
.then(function (result) { return that.callback(null, result); });
},
"should respond with overrides": function (err, results) {
assert.isNull(err);
assert.deepEqual(results, { xyz: 468, abc: 123 });
}
}
}
}).addBatch({
"When using prompt": {
"with fancy properties": {
Expand Down

0 comments on commit 8d5495c

Please sign in to comment.