This content originally appeared on DEV Community and was authored by Mitchell
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
This content originally appeared on DEV Community and was authored by Mitchell
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.
APA
MLA
Mitchell | Sciencx (2024-11-04T02:12:51+00:00) Callback – JavaScript Challenges. Retrieved from https://www.scien.cx/2024/11/04/callback-javascript-challenges/
" » Callback – JavaScript Challenges." Mitchell | Sciencx - Monday November 4, 2024, https://www.scien.cx/2024/11/04/callback-javascript-challenges/
HARVARDMitchell | Sciencx Monday November 4, 2024 » Callback – JavaScript Challenges., viewed ,<https://www.scien.cx/2024/11/04/callback-javascript-challenges/>
VANCOUVERMitchell | Sciencx - » Callback – JavaScript Challenges. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/11/04/callback-javascript-challenges/
CHICAGO" » Callback – JavaScript Challenges." Mitchell | Sciencx - Accessed . https://www.scien.cx/2024/11/04/callback-javascript-challenges/
IEEE" » Callback – JavaScript Challenges." Mitchell | Sciencx [Online]. Available: https://www.scien.cx/2024/11/04/callback-javascript-challenges/. [Accessed: ]
rf:citation » Callback – JavaScript Challenges | Mitchell | Sciencx | https://www.scien.cx/2024/11/04/callback-javascript-challenges/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.