Asynchronous JavaScript Patterns Working With Callbacks | by Sebas Quiroga | Feb, 2022

A look at the Callback design pattern

Sebas Quiroga
Photo by Firmbee.com on Unsplash
function foo(a, b) {
console.info(a + b); // 3
}
foo(1,2);
function sum(a, b){
return a + b;
}
// A function that orchestrates
function foo(callback, a , b){
return callback(a,b) // this line will call our sum()
}

// we pass the reference of the function sum() and two numbers
const resp = foo(sum, 1, 2)
console.info(resp); // 3```
function sum(a, b){
return a + b;
}
// New Subtract function
function sub(a, b){
return a — b;
}
function foo(callback, a , b){
return callback(a,b) // this line will call either sum() or sub()
}
const respSum = foo(sum, 1, 2);
const respSub = foo(sub, 1, 2); // We can now subtract too!
console.info(` Sum: ${respSum}` ); // 3
console.info(` Sub: ${respSub}`); // -1

function fetchFoo() {
setTimeout(() => {
console.info(‘First Line’)
}, 2000)
console.info(‘Second Line’)
}
fetchFoo()
// Chaining callbacks as a way of forcing sequential executionfunction fooBar() {
cb1()
function cb1() {
setTimeout(function () {
console.info(‘First Line’)
cb2()
}, 1000)
function cb2() {
console.info(‘Second Line’)
}
}
}
fooBar()
function fooBar(cb1) {
setTimeout(function () {
// The function cb1() expects another callback — the cb2()
cb1(function cb2 () {
console.info(‘Second Line’)
})
}, 1000)
}
// The function cb1() will eventually read and execute another callback that is not still defined.
// We will eventually define it with the next sequential instructions.
fooBar(function cb1 (cb2) {
console.info(‘First Line’)
cb2()
})

Leave a Comment