Skip to content

Better support for promises #196

Open
@jpmonette

Description

@jpmonette

It would be great to support promises without having to rely on the promiser, in order to:

  • simplify typing (especially if there is a shift to TypeScript codebase);
  • support functions that have a different order of arguments (such as sendRequest, where successCB and errorCB are not the last arguments)
export const sendRequest = <T>(
  endPoint: string,
  path: string,
  successCB: ExecSuccessCallback<T>,
  errorCB: ExecErrorCallback,
  method?: HttpMethod,
  payload?: Record<string, unknown> | null,
  headerParams?: Record<string, unknown> | null,
  fileParams?: unknown,
  returnBinary?: boolean,
  doesNotRequireAuthentication?: boolean,
): void => {

This would require to add a type check in each function to see if the callbacks have been provided. If not, the function could return a Promise.

Here's a sample implementation for the query function:

type QueryOverload = {
  /**
   * Executes the specified SOQL query.
   * @param soql a string containing the query to execute - e.g. "SELECT Id,
   *             Name from Account ORDER BY Name LIMIT 20"
   * @param callback function to which response will be passed
   * @param [error=null] function called in case of error
   * @returns void
   */
  <T>(soql: string, successCB: ExecSuccessCallback<T>, errorCB: ExecErrorCallback): void;
  /**
   * Executes the specified SOQL query.
   * @param soql a string containing the query to execute - e.g. "SELECT Id,
   *             Name from Account ORDER BY Name LIMIT 20"
   * @returns Promise<T>
   */
  <T>(soql: string): Promise<T>;
};

export const query: QueryOverload = <T>(soql: string, successCB?: ExecSuccessCallback<T>, errorCB?: ExecErrorCallback): any => {
  if (successCB && errorCB) {
    sendRequest("/services/data", `/${apiVersion}/query`, successCB, errorCB, "GET", { q: soql });
  } else {
    return new Promise((resolve, reject) => {
      const successCallback = (results: T) => resolve(results);
      const errorCallback: ExecErrorCallback = (error) => reject(error);
      sendRequest("/services/data", `/${apiVersion}/query`, successCallback, errorCallback, "GET", { q: soql });
    });
  }
};

query("SELECT Id FROM Account")
  .then((results) => console.log(results))
  .catch((err) => console.error(err));

query(
  "SELECT Id FROM Account",
  (results) => console.log(results),
  (err) => console.error(err),
);

And of course, we would benefit from the IntelliSense for both versions of the function.

Capture d’écran, le 2020-08-04 à 11 06 23

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions