Callbacks and Promises in Javascript
satya - 11/29/2024, 8:28:50 PM
About
satya - 11/29/2024, 8:55:45 PM
Arrow and anonymous functions
satya - 11/29/2024, 8:59:58 PM
Code snippets to explain all these variations
// 1. Function Expressions
// Anonymous Function Expression
const add = function (a, b) {
return a + b;
};
console.log(add(2, 3)); // 5
// Named Function Expression
const multiply = function multiplyFunc(a, b) {
return a * b;
};
console.log(multiply(2, 3)); // 6
// Immediately Invoked Function Expression (IIFE)
(function () {
console.log("IIFE called immediately!");
})(); // Output: IIFE called immediately!
// 2. Arrow Functions
// Single-Parameter Arrow Function (Implicit Return)
const square = x => x * x;
console.log(square(4)); // 16
// Multiple Parameters (Explicit Return)
const subtract = (a, b) => {
return a - b;
};
console.log(subtract(5, 2)); // 3
// No Parameters
const greet = () => "Hello, World!";
console.log(greet()); // Hello, World!
// Arrow Function Returning an Object
const createUser = (name, age) => ({ name, age });
console.log(createUser("Alice", 25)); // { name: "Alice", age: 25 }
// Arrow Function with Rest Parameters
const sum = (...nums) => nums.reduce((total, num) => total + num, 0);
console.log(sum(1, 2, 3, 4)); // 10
// Arrow Function as a Callback
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
// 3. Function Context and `this`
// Regular Function with `this`
const obj = {
value: 10,
regularFunction: function () {
console.log(this.value); // `this` refers to obj
},
};
obj.regularFunction(); // 10
// Arrow Function with `this`
const obj2 = {
value: 10,
arrowFunction: () => {
console.log(this.value); // `this` refers to the outer context
},
};
obj2.arrowFunction(); // undefined (or error in strict mode)
// 4. Advanced Arrow Function Syntax
// Chained Arrow Functions
const addChained = a => b => c => a + b + c;
console.log(addChained(1)(2)(3)); // 6
// Arrow Function in Object Methods (Caution with `this`)
const obj3 = {
value: 42,
method: () => {
console.log(this.value); // `this` does not refer to obj3
},
};
obj3.method(); // undefined
// Event Listener with Arrow Function
document.body.addEventListener("click", () => {
console.log("Body clicked!");
});
// 5. Differences in `arguments`
// Regular Function Using `arguments`
function logArguments() {
console.log(arguments); // [Arguments] { '0': 1, '1': 2, '2': 3 }
}
logArguments(1, 2, 3);
// Arrow Function and Rest Parameters
const logArgumentsArrow = (...args) => {
console.log(args); // [1, 2, 3]
};
logArgumentsArrow(1, 2, 3);
// 6. Immediately Returning Arrow Function
// Simple Implicit Return
const triple = x => x * 3;
console.log(triple(3)); // 9
// Returning an Object
const getObject = () => ({ key: "value" });
console.log(getObject()); // { key: "value" }
satya - 11/29/2024, 9:07:59 PM
The prototypical arrow function
const square = x => x * x;
console.log(square(4)); // 16
satya - 11/29/2024, 9:09:37 PM
Explanation
satya - 11/29/2024, 9:10:50 PM
It will look like the following
const square = (x) => {
return x * x;
};
satya - 11/29/2024, 9:12:44 PM
One with no arguments
// No Parameters
const greet = () => "Hello, World!";
console.log(greet()); // Hello, World!
satya - 11/29/2024, 9:14:58 PM
A more complicated example
// Arrow Function with Rest Parameters
const sum = (...nums) => nums.reduce((total, num) => total + num, 0);
console.log(sum(1, 2, 3, 4)); // 10
satya - 11/29/2024, 9:19:24 PM
Explanation
satya - 11/29/2024, 9:20:31 PM
If you read the lines above and get used to understanding their structure, you have it
satya - 11/29/2024, 9:21:06 PM
What are higher order functions? Read the following if you need further explanation
What are higher order functions?
satya - 11/29/2024, 9:22:36 PM
In summary, best way to read arrow functions
satya - 11/29/2024, 9:28:47 PM
Javascript arrow function: See syntax of these as images
satya - 11/30/2024, 9:24:23 AM
The three ways of asyncing in JS
satya - 11/30/2024, 9:27:17 AM
Here is an async call back example that deals with both success and failiure
// Define a function that accepts success and error callbacks
function fetchData(callback, errorCallback) {
const success = false; // Simulate an error scenario
if (success) {
callback("Data received!");
} else {
errorCallback("Error fetching data.");
}
}
// Call the function with success and error callbacks
fetchData(
(message) => {
console.log(message); // Success callback
},
(error) => {
console.error(error); // Error callback
}
);
satya - 11/30/2024, 9:32:20 AM
Notes on traditional callbacks
satya - 11/30/2024, 9:35:06 AM
Here is an older filesystem calls in node.js does this
const fs = require("fs");
fs.readFile("example.txt", "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
} else {
console.log("File content:", data);
}
});
satya - 11/30/2024, 9:35:42 AM
Notice
satya - 11/30/2024, 9:36:50 AM
Here is how they are used in streaming.....nice example
const fs = require("fs");
const stream = fs.createReadStream("example.txt");
stream.on("data", chunk => {
console.log("Chunk received:", chunk);
});
stream.on("end", () => {
console.log("No more data.");
});
satya - 11/30/2024, 9:37:44 AM
Here is what happens there are multiple asyncs....
getData((err, data) => {
if (err) return console.error(err);
processData(data, (err, processed) => {
if (err) return console.error(err);
saveData(processed, (err) => {
if (err) return console.error(err);
console.log("All done!");
});
});
});
satya - 11/30/2024, 9:38:30 AM
Notice the intentions
satya - 11/30/2024, 9:39:26 AM
This is done better using promises or a language that is closer to the intention
getData()
.then(processData)
.then(saveData)
.then(() => console.log("All done!"))
.catch(err => console.error(err));
//Each method returns a promise for chaining the thens