const users = [
{
id: '123',
name: 'John Smith',
posts: [
{title: 'Some amazing title', content: 'Here is some amazing content'},
{title: 'My favorite title', content: 'My favorite content'},
{title: 'A not-so-good title', content: 'The not-so-good content'},
]
},
{
id: '456',
name: 'Mary Michaels',
posts: [
{title: 'Some amazing title', content: 'Here is some amazing content'},
{title: 'My favorite title', content: 'My favorite content'},
{title: 'A not-so-good title', content: 'The not-so-good content'},
]
},
]
function getUserPosts(id, cb) {
const user = users.find(el => el.id === id);
if (cb) {
if (user) {
return cb(null, user);
}
return cb('User Not Found', null);
}
return new Promise(function(resolve, reject){
if (user) {
resolve(user);
} else {
reject('User not found');
}
});
}
/* The above code is collapsed to simulate an API you might use to get user posts for a
* particular user from a database.
* The API can take a callback as a second argument: getUserPosts(<id>, <callback>);
* The callback function first argument is any error and second argument is the user.
* For example:
getUserPosts('123', function(err, user) {
if (err) {
console.log(err)
} else {
console.log(user);
}
});
* getUserPosts also returns a promise, for example: getUserPosts.then().catch();
* The ID's that will generate a user are the of type string and they are '123' and '456'.
* All other IDs will return an error.
*/
getUserPosts('123', function(err, user) {
if (err) {
console.log(err);
} else {
console.log(user);
}
});
getUserPosts('129', function(err, user) {
if (err) {
console.log(err);
} else {
console.log(user);
}
});
getUserPosts('456')
.then(user => console.log(user))
.catch(err => console.log(err));
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.