8. Asynchronous Programming
Activity 11: Using Callbacks to Receive Results
Solution:
- Create a
calculate
function that takesid
and acallback
as an argument:function calculate(id, callback) { }
- We will first call
getUsers
to get all of the users. This will give us the address we need:function calculate(id, callback) { clientApi.getUsers((error, result) => { if (error) { return callback(error); } const currentUser = result.users.find((user) => user.id === id); if (!currentUser) { return callback(new Error('user not found')); } }); }
Here, we get all of the users, then we apply the
find
method to theuser
to find the user we want from the list. If that user does not exist, we call thecallback
function with theUser not found
error. - Call
getUsage
to get the user's usage:clientApi.getUsage(id, (error, usage) => { if (error) { return callback(error); } });
Then, we need to put the call to
getUsage
inside the callback of...