您可以在倉庫 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中文網其他相關文章!