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...");
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Received user data...");
resolve({ ID: id, "Account number": "58721094531267" });
}, 2000);
});
}
Note that I've ignored the case where the Promise may be "rejected" to keep the example concise.
Now, as an exercise, update how getUser
is employed. (Hint: you must consume a Promise
).
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, (user) => console.log(user)); // TODO update me! 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);
});
}
console.log("listening for events");
getUser(1)
.then((user) => console.log(user));
console.log("still listening for events!");