DEV Community

Mitchell
Mitchell

Posted on

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

Top comments (0)