Skip to content

Instantly share code, notes, and snippets.

@robrich
Last active October 15, 2018 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robrich/5297e4918b64eeccd1b74cd417ff8b3f to your computer and use it in GitHub Desktop.
Save robrich/5297e4918b64eeccd1b74cd417ff8b3f to your computer and use it in GitHub Desktop.
Move from promises to async/await
import delay from './delay';
import { authors } from './authorData'
//This would be performed on the server in a real app. Just stubbing in.
let maxid = authors.reduce(((currentMax, {id}) => currentMax>id ? currentMax : id), 0 );
const generateId = (author) => {
return ++maxid;
};
const sleep = function (timeout) {
return new Promise((resolve) => setTimeout(resolve, timeout));
};
class AuthorApi {
static async getAllAuthors() {
await sleep(delay);
return Object.assign([], authors); // so users can change their copy without breaking this list
}
static async saveAuthor(author) {
author = Object.assign({}, author); // to avoid manipulating object passed in.
await sleep(delay);
// Simulate server-side validation
const minAuthorNameLength = 3;
if (author.firstName.length < minAuthorNameLength) {
throw new Error(`First Name must be at least ${minAuthorNameLength} characters.`);
}
if (author.lastName.length < minAuthorNameLength) {
throw new Error(`Last Name must be at least ${minAuthorNameLength} characters.`);
}
if (author.id) {
const existingAuthorIndex = authors.findIndex(a => a.id === author.id);
authors.splice(existingAuthorIndex, 1, author);
} else {
//Just simulating creation here.
//The server would generate ids for new authors in a real app.
//Cloning so copy returned is passed by value rather than by reference.
author.id = generateId();
authors.push(author);
}
return author;
}
static async deleteAuthor(authorId) {
await sleep(delay);
const indexOfAuthorToDelete = authors.findIndex(author => (
author.id === authorId)
);
authors.splice(indexOfAuthorToDelete, 1);
}
}
export default AuthorApi;
var theData = {
authors:
[
{
id: '1',
firstName: 'Stephen',
lastName: 'King'
},
{
id: '2',
firstName: 'J.K.',
lastName: 'Rowlings'
},
{
id: '3',
firstName: 'John',
lastName: 'Grisham'
}
]
};
export default theData;
export var authors = theData.authors;
export default 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment