Skip to content

Latest commit

 

History

History
64 lines (51 loc) · 1.63 KB

promisify-a-callback.mo.md

File metadata and controls

64 lines (51 loc) · 1.63 KB

[MO] Promisify a callback (~5 min)

Owner: Arthur Levoyer

Why

When an asynchronous action is performed, if you want to wait for its success or failure and avoid several chains of callbacks. See callback hell.

Steps

  • I identified the asynchronous call I want to wait for
  • I included the function into a callback, the executor of the Promise will handle an asynchronous work (in the examples below the describeTable). Once the work is done, if it went well, we are calling the resolve function, if not we are calling the reject one.

Examples

Example 1: Bad example

export const waitForCallbackToBeSolved = () => {
  asynchronousAction(params, (error, data) => {
    // We create a Promise with the function using a callback in second arguments
    if (error) throw error;
    else console.log(data);
  });
};

export const getResponse = async () => {
  try {
    await waitForCallbackToBeSolved();
    doStuff();
  } catch (error) {
    log(error);
    throw error;
  }
};

-> [ ] Neither Promise nor promisify had been used hence we are sending a 200 status in all cases

Example 2: Good example

export const waitForCallbackToBeSolved = () => {
  return new Promise((resolve, reject) => {
    // We create a Promise with the function using a callback in second argument
    asynchronousAction(params, (error, data) => {
      if (error) {
        return reject(error);
      }
      resolve(data);
    });
  });
};

export const getResponse = async () => {
  try {
    await waitForCallbackToBeSolved();
    doStuff();
  } catch (error) {
    log(error);
    throw error;
  }
};