Home  >  Article  >  Web Front-end  >  Callback - JavaScript Challenges

Callback - JavaScript Challenges

DDD
DDDOriginal
2024-11-04 17:07:02692browse

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);

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'
});


Reference

  • Callback (computer programming) - Wikipedia.org
  • Callback function - MDN
  • Thunk - Wikipedia.org
  • 54. flatten Thunk - BFE.dev

The above is the detailed content of Callback - JavaScript Challenges. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn