Replacing Callbacks with Promises
Here is the code which exhibits the callback pattern for dialing with async work:
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!");
We are going to replace the callback pattern with the Promise pattern. As a first step, we must update our async function getUser
to return a Promise.
function getUser(id) {
console.log(`Reading a user from a database!`);
const promise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
console.log(`Recieved user data!`);
resolve({ "ID": id, "Account number": "58721094531267" });
} else {
reject(new Error("Could not read the user data!"));
}
}, 2000);
})
return promise;
}
Exercise Update how getUser
is employed. (Hint: you must consume a Promise
).
function getUser(id) { console.log(`Reading a user from a database!`); const promise = new Promise((resolve, reject) => { const success = true; setTimeout(() => { if (success) { console.log(`Recieved user data!`); resolve({ "ID": id, "Account number": "58721094531267" }); } else { reject(new Error("Could not read the user data!")); } }, 2000); }) return promise; } console.log("listening for events"); getUser(1, (user) => console.log(user)); // TODO update me! console.log("still listening for events!");
Solution
console.log("listening for events!");
getUser(1)
.then(user => console.log(user))
.catch(err => console.log(err.message));
console.log("still listening for events!");