So, the first project is not very real-world, but it is going to be a great way to learn the new syntax. Then we're going to move on to another little project where you're going to be required to make two actual API calls from some APIs I picked out. Those will be asynchronous and we'll use async/await there. To wrap things up, we're going to add a little bit of async/await code back into the todo API.
So, to kick things off, we're going to go through this very contrived example and we can start by creating a few users to work with. Each user object is going to have a few properties; we'll start off with an id, just like they would have inside of a real database. I'm going to give this one an id of 1:
const users = [{
id: 1,
}];
const grades = [];
We'll also have a name, a string name for the user. I'm going to call the first one Andrew and then we're going to move on to the final property, a schoolId, an ID that will change as the student switches from one school to another. We can just make up another id for this one. I'm going to go ahead and start at 101:
const users = [{
id: 1,
name: 'Andrew',
schoolId: 101
}];
const grades = [];
Now that we have user number 1 created' let's go ahead and clone him. I'm going to copy it, toss a comma and paste it, and we'll create just one more user for this example. This one will have an id of 2. We'll change the name from Andrew over to something like Jessica and we'll give her a schoolId of 999:
const users = [{
id: 1,
name: 'Andrew',
schoolId: 101
}, {
id: 2,
name: 'Jessica',
schoolId: 999
}];
const grades = [];
Now that we have some users in place, we're going to create our first of three functions we'll be building in this section. This one is called const getUser. It is going to take the id of the user, find that user, and return the user object:
const grades = [];
const getUser = [id] => {
};
So, if the id is 1, we're going to get this object:
const users = [{
id: 1,
name: 'Andrew',
schoolId: 101
},
If it's 2, I'm going to get this object back:
{
id: 2,
name: 'Jessica',
schoolId: 999
}];
If it's 3 or some other id that doesn't exist, I'm going to actually have an error thrown. So, this is going to return a promise of resolve if the id is a match with one of the users, or reject if it's not.
Now, as I mentioned, this is a contrived example, so we're going to be creating new promises explicitly. I'm going to create a new promise, passing in that promise function which, as you remember, gets called with resolve and reject:
const getUser = (id) => {
return new Promise((resolve, reject) => {
});
};
Then we're going to go ahead and add a little bit of logic in the function.