Skip to content

Commit

Permalink
Precompute _shouldAwait to avoid repeating costly computation
Browse files Browse the repository at this point in the history
  • Loading branch information
aweebit committed Jul 26, 2023
1 parent 254865c commit e66eda5
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions lib/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ class Command extends EventEmitter {
this._asyncParsing = undefined;
/** @type {boolean | undefined} */
this._await = undefined;
/** @type {boolean | undefined} */
this._shouldAwait = undefined;

// see .configureOutput() for docs
this._outputConfiguration = {
Expand Down Expand Up @@ -304,7 +306,7 @@ class Command extends EventEmitter {
*/

_parseArg(target, value, previous, handleError) {
const handleThenableError = this._shouldAwait() ? handleError : undefined;
const handleThenableError = this._shouldAwait ? handleError : undefined;

try {
if (this._shouldChainArgParserCalls(target)) {
Expand Down Expand Up @@ -959,6 +961,7 @@ Expecting one of '${allowedValues.join("', '")}'`);

parse(argv, parseOptions) {
this._asyncParsing = false;
this._setShouldAwait();

try {
const userArgs = this._prepareUserArgs(argv, parseOptions);
Expand All @@ -967,6 +970,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
return this;
} finally {
this._asyncParsing = undefined;
this._shouldAwait = undefined;
}
}

Expand All @@ -991,6 +995,7 @@ Expecting one of '${allowedValues.join("', '")}'`);

async parseAsync(argv, parseOptions) {
this._asyncParsing = true;
this._setShouldAwait();

try {
const userArgs = this._prepareUserArgs(argv, parseOptions);
Expand All @@ -999,6 +1004,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
return this;
} finally {
this._asyncParsing = undefined;
this._shouldAwait = undefined;
}
}

Expand All @@ -1021,14 +1027,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
* @api private
*/

_shouldAwait() {
let shouldAwait;
let cmd = this;
do {
shouldAwait = cmd._await ?? cmd._asyncParsing;
cmd = cmd.parent;
} while (shouldAwait === undefined);
return shouldAwait;
_setShouldAwait() {
for (let cmd = this; this._shouldAwait === undefined; cmd = cmd.parent) {
this._shouldAwait = cmd._await ?? cmd._asyncParsing;
}
}

/**
Expand Down Expand Up @@ -1078,7 +1080,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
*/

_optionalAwait(getPromises) {
if (this._shouldAwait()) {
if (this._shouldAwait) {
const toAwait = getPromises();
if (toAwait.length) return Promise.all(toAwait);
}
Expand Down

0 comments on commit e66eda5

Please sign in to comment.