您可以在仓库 Github 上找到本文中的所有代码。
/** * @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);
/** * @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' });
以上是回调 - JavaScript 挑战的详细内容。更多信息请关注PHP中文网其他相关文章!