Skip to content

Commit

Permalink
feat: async command handlers (#1001)
Browse files Browse the repository at this point in the history
  • Loading branch information
zenflow authored and bcoe committed Jan 1, 2018
1 parent 6f4640d commit 241124b
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 7 deletions.
8 changes: 4 additions & 4 deletions docs/api.md
Expand Up @@ -664,10 +664,10 @@ Examples will be printed out as part of the help message.
<a name="exitprocess"></a>.exitProcess(enable)
----------------------------------

By default, yargs exits the process when the user passes a help flag, uses the
`.version` functionality, or when validation fails. Calling
`.exitProcess(false)` disables this behavior, enabling further actions after
yargs have been validated.
By default, yargs exits the process when the user passes a help flag, the user
uses the `.version` functionality, validation fails, or the command handler
fails. Calling `.exitProcess(false)` disables this behavior, enabling further
actions after yargs have been validated.

<a name="fail"></a>.fail(fn)
---------
Expand Down
8 changes: 7 additions & 1 deletion lib/command.js
Expand Up @@ -232,7 +232,13 @@ module.exports = function command (yargs, usage, validation) {
}, {})
Object.assign(innerArgv, middlewareArgs)
}
commandHandler.handler(innerArgv)
const handlerResult = commandHandler.handler(innerArgv)
if (handlerResult && typeof handlerResult.then === 'function') {
handlerResult.then(
null,
(error) => yargs.getUsageInstance().fail(null, error)
)
}
}

if (command) {
Expand Down
4 changes: 2 additions & 2 deletions lib/usage.js
Expand Up @@ -46,9 +46,9 @@ module.exports = function usage (yargs, y18n) {
if (!failureOutput) {
failureOutput = true
if (showHelpOnFail) yargs.showHelp('error')
if (msg) logger.error(msg)
if (msg || err) logger.error(msg || err)
if (failMessage) {
if (msg) logger.error('')
if (msg || err) logger.error('')
logger.error(failMessage)
}
}
Expand Down
13 changes: 13 additions & 0 deletions test/command.js
Expand Up @@ -1402,4 +1402,17 @@ describe('Command', () => {
}).to.throw(/.*\.usage\(\) description must start with \$0.*/)
})
})

// addresses https://github.com/yargs/yargs/issues/510
it('fails when the promise returned by the command handler rejects', (done) => {
const error = new Error()
yargs('foo')
.command('foo', 'foo command', noop, (yargs) => Promise.reject(error))
.fail((msg, err) => {
expect(msg).to.equal(null)
expect(err).to.equal(error)
done()
})
.argv
})
})

0 comments on commit 241124b

Please sign in to comment.