DEV Community

Mitchell
Mitchell

Posted on

1

Callback - JavaScript Challenges

You can find all the code in this post at the repo Github.


Async programming callback related challenges


Invoke a callback after a specific second

/**
 * @param {function} callbackFn
 * @param {delay} number
 * @return {object}
 */

function invokeLater(callbackFn, delay) {
  const timerId = setTimeout(() => {
    callbackFn(null, 'run');
  }, delay);

  return {
    clear: () => clearTimeout(timerId),
  }
}

// Usage example
const cancel = invokeLater((err, data) => {
  console.log(data);
  cancel.clear();
}, 2000);
Enter fullscreen mode Exit fullscreen mode

Flatten thunk

/**
 * @param {function} fn
 * @return {function}
 */

function flattenThunk(fn) {
  return function (callbackFn) {
    function resolveThunk(err, result) {
      if (err) {
        callbackFn(err, undefined);
        return;
      }

      if (typeof result === 'function') {
        result(resolveThunk);
      } else {
        callbackFn(undefined, result);
      }
    }

    fn(resolveThunk);
  }
}

// Usage example
function fn1(callbackFn) {
  setTimeout(() => {
    callbackFn(null, 'ok');
  }, 10);
}

function fn2(callbackFn) {
  setTimeout(() => {
    callbackFn(null, fn1);
  }, 10);
}

function fn3(callbackFn) {
  setTimeout(() => {
    callbackFn(null, fn2);
  }, 10);
}

flattenThunk(fn3)((err, data) => {
  console.log(data); // 'ok'
});

Enter fullscreen mode Exit fullscreen mode

Reference

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more