Callback
Callback is a function that is called when the result of an asynchronous operation is ready.
function getUser(id, callback) { console.log("Reading a user from a database..."); setTimeout(() => { console.log("Received user data..."); callback({ "ID": id, "Account number": "58721094531267" }); }, 2000); } console.log("listening for events"); getUser(1, (user) => console.log(user)); console.log("still listening for events!");
Exercise Add an asynchronous function, getLoans
, that simulates sending an HTTP GET request to a bank, providing the account number, to receive a list of loans associated with the given account.
Use the callback pattern to display the loans.
function getUser(id, callback) { console.log("Reading a user from a database..."); setTimeout(() => { console.log("Received user data..."); callback({ "ID": id, "Account number": "58721094531267" }); }, 2000); } function getLoans(account) { // TODO update this to an asynchronous function return ["loan 1", "loan 2", "loan 3"]; } console.log("listening for events"); getUser(1, (user) => { console.log(user); // TODO call getLoans and display the returned values }); console.log("still listening for events!");
Solution
function getUser(id, callback) {
console.log("Reading a user from a database...");
setTimeout(() => {
console.log("Received user data...");
callback({ "ID": id, "Account number": "58721094531267" });
}, 2000);
}
function getLoans(account, callback) {
console.log("Sending HTTP GET request to a bank...");
setTimeout(() => {
console.log("Received loan data...");
callback(["loan 1", "loan 2", "loan 3"]);
}, 2000);
}
console.log("listening for events");
getUser(1, (user) => {
console.log(user);
getLoans(user["Account number"], (loans) => {
console.log(loans);
})
});
console.log("still listening for events!");