The first thing we need to do is try to find a match and I'm going to use the array find method to get that done. We'll create a const user to store the match, then we'll set it equal to users.find, passing in our function:
const getUser = (id) => {
return new Promise((resolve, reject) => {
const user = user.find(() = {
});
});
};
Now this function gets called one time for every item in the array. It's an array of users so we can call the individual item user. If we return true, it is going to consider that a match. It'll stop and it'll set that object on a user. If we return false, it'll continue on through the array and, if none are matched, undefined will be the value for user. So, we're just going to return user.id, checking if it equals the id passed in.
const getUser = (id) => {
return new Promise((resolve, reject) => {
const user = user.find((user) => {
return user.id === id;
});
});
};
Now, we have a great candidate for the shorthand syntax here. We just have an arrow function that returns some value. It just provides the value and have it be implicitly returned:
const getUser = (id) => {
return new Promise((resolve, reject) => {
const user = user.find((user) => user.id === id);
Here we have the exact same functionality. Now, before we go ahead and use it, let's go ahead and actually call resolve or reject. If there is a user, we're going to do one thing; if there's not a user, that's fine, we're just going to do something else. In the else statement, we'll be calling reject and, in if statement, we'll be calling resolve:
const getUser = (id) => {
return new Promise((resolve, reject) => {
const user = user.find((user) => user.id === id);
if (user) {
resolve();
} else {
reject();
}
});
};
Now, resolve is just going to have the user passed in and, for reject, we can come up with an error message that helps the user figure out what went wrong. We can add unable to find user with id of ., then, we'll put the id next to it. Inside the template string, I'm going to reference id. This is the exact value that was passed in the getUser variable.
const getUser = (id) => {
return new Promise((resolve, reject) => {
const user = user.find((user) => user.id === id);
if (user) {
resolve(user);
} else {
reject('Unable to find user with id of ${id}.');
}
});
};
Now, before we go ahead and actually run this, let's just use getUser real quick. I'm going to call getUser with an id of 2, which should return Jessica. I'll add on then and catch. Inside catch, we can catch that error. We're just going to get the error and log it out, console.log(e).
getUser(2).then().catch((e) => {
console.log(e);
});
Then we can set up our then callback; inside then, we're going to get access to the user and, for now, we'll just log it out:
getUser(2).then((user) => {
console.log(user);
}).catch((e) => {
console.log(e);
});