Promises Exercise
As a reference, here is the earlier work we had done for getUser
:
Callback pattern
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!");
Promise pattern
function getUser(id) {
console.log("Reading a user from a database...");
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Received user data...");
resolve({ ID: id, "Account number": "58721094531267" });
}, 2000);
});
}
console.log("listening for events");
getUser(1)
.then((user) => console.log(user));
console.log("still listening for events!");
Exercise: Update the following code to use Promises instead of callbacks.
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("Request for loan data..."); setTimeout(() => { console.log("Received loan data..."); callback({ "Most recent": "loan 3", All: ["loan 1", "loan 2", "loan 3"] }); }, 2000); } function getTransactions(loan, callback) { console.log("Request for transactions data..."); setTimeout(() => { console.log("Received transactions data..."); callback(["tran 3", "tran 2", "tran 1"]); }, 2000); } console.log("listening for events"); getUser(1, (user) => { getLoans(user["Account number"], (loans) => { getTransactions(loans["Most recent"], (transactions) => { console.log(transactions); }); }); }); console.log("still listening for events!");
Solution
function getUser(id) {
console.log("Reading a user from a database...");
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Received user data...");
resolve({ ID: id, "Account number": "58721094531267" });
}, 2000);
});
}
function getLoans(account) {
console.log("Request for loan data...");
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Received loan data...");
resolve({ "Most recent": "loan 3", All: ["loan 1", "loan 2", "loan 3"] });
}, 2000);
});
}
function getTransactions(loan) {
console.log("Request for transactions data...");
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Received transactions data...");
resolve(["tran 3", "tran 2", "tran 1"]);
}, 2000);
});
}
console.log("listening for events");
getUser(1)
.then((user) => getLoans(user["Account number"]))
.then((loans) => getTransactions(loans["Most recent"]))
.then((transactions) => {
console.log(transactions);
});
console.log("still listening for events!");