From 9a42b6380c92a3528a1e47ebf2ed0354e723fea2 Mon Sep 17 00:00:00 2001 From: Mael Le Guen Date: Wed, 18 Sep 2019 23:20:14 +0200 Subject: [PATCH] fix: async middleware was called twice (#1422) --- lib/middleware.js | 3 +-- test/middleware.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lib/middleware.js b/lib/middleware.js index 9f9c19696..56dab7527 100644 --- a/lib/middleware.js +++ b/lib/middleware.js @@ -40,8 +40,7 @@ function applyMiddleware (argv, yargs, middlewares, beforeValidation) { const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true') return middlewares .reduce((accumulation, middleware) => { - if (middleware.applyBeforeValidation !== beforeValidation && - !isPromise(accumulation)) { + if (middleware.applyBeforeValidation !== beforeValidation) { return accumulation } diff --git a/test/middleware.js b/test/middleware.js index dd6638c4e..5ea318935 100644 --- a/test/middleware.js +++ b/test/middleware.js @@ -145,6 +145,36 @@ describe('middleware', () => { .exitProcess(false) .parse() }) + + it('calls an async middleware only once for nested subcommands', (done) => { + let callCount = 0 + let argv = yargs('cmd subcmd') + .command( + 'cmd', + 'cmd command', + function (yargs) { + yargs.command( + 'subcmd', + 'subcmd command', + function (yargs) {} + ) + } + ) + .middleware((argv) => new Promise((resolve) => { + callCount++ + resolve(argv) + })) + .parse() + + if (!(argv instanceof Promise)) done('argv should be a Promise') + + argv + .then(() => { + callCount.should.equal(1) + done() + }) + .catch(err => done(err)) + }) }) // see: https://github.com/yargs/yargs/issues/1281