Search This Blog

2024/03/24

Javascript : Callback using Closure an Example

create database folder.add three files sagar.json,sangram.json,sachin.json.

sagar.json

{
"secret":"He punched his brother when mother is not around"
}

sangram.json

{
"secret":"He is running around to fix the problem"
}

sachin.json
{
"secret":"He eats rest of ice cream"
}

closure.js

Code:
"use strict";
const fs = require("fs");

let users = [
{
username: "sagar",
password: "ssd1778",
},
{
username: "sangram",
password: "ssd1110",
},
{
username: "sachin",
password: "ssd2183",
},
];

let printResult = function (username, secret) {
console.log(`USERNAME:${username},SECRET:${secret}`);
};

let callback = function (username) {
return function (err, response) {
if (err) {
throw new Error(err);
}
let data = JSON.parse(response);
let secret = data["secret"];
printResult(username, secret);
};
};

let getSecret = function (users) {
users.forEach((obj) => {
fs.readFile("./database/" + obj.username + ".json", "utf8",
callback(obj.username));
});
};

getSecret(users);


Output:
USERNAME:sagar,SECRET:He punched his brother when mother is not around
USERNAME:sangram,SECRET:He is running around to fix the problem
USERNAME:sachin,SECRET:He eats rest of ice cream

Explanation:
'callback()' function returns function,it's inner function remember value of
variable 'username' which is function parameter of 'callback()' function.
then this inner function 'printResult()' print results.


No comments:

Post a Comment