Skip to content

Refactor commandAction to return a Promise #3430

@martinlingstuyl

Description

@martinlingstuyl

Say we would refactor the commandAction function to return a Promise.

...we could then use async/await for all functions and directly await them from commandAction.

...we could use the cb() function to resolve that promise.

...we could move try catch logic down to the base command, so we don't need to call this.handleRejectedODataJsonPromise(rawRes, logger, cb)) in every command file.

For example:

public commandAction(logger: Logger, args: any, cb: () => void): void {
  const requestOptions: any = { /* ... */  };

  request
    .get<{ value: any[] }>(requestOptions)
    .then((res: { value: any[] }): void => {
      logger.log(res.value);
      cb();
    }, (rawRes: any): void => this.handleRejectedODataJsonPromise(rawRes, logger, cb));
}

Could be refactored to

public async commandAction(logger: Logger, args: any, cb: () => void): Promise<void> {    
  const requestOptions: any = { /* ... */ };

  const res = await request.get<{ value: any[] }>(requestOptions);      
  logger.log(res.value);
  cb(); //Not even strictly necessary, but for backwards compatibility it could be used.             
}

Refactoring can be spread over time, the promise chain that is used in commandAction can just be returned instead of refactoring everything to async/await right away. This would make an initial refactoring rather small.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions