Skip to content

Instantly share code, notes, and snippets.

@wolverineks
Last active May 6, 2018 13:48
Show Gist options
  • Save wolverineks/80b45f0cecf6ab7eab14b84d051cc6d8 to your computer and use it in GitHub Desktop.
Save wolverineks/80b45f0cecf6ab7eab14b84d051cc6d8 to your computer and use it in GitHub Desktop.
Recreating Async / Await
// Types ///////////////////////////////////////////////////////////////////
type BookId = string
type BookTitle = string
type BookAuthor = string
type BookRating = number
type AuthorName = string
type AuthorId = number
type Author = {
name: AuthorName,
id: AuthorId
}
type Book = {
id: BookId,
title: BookTitle,
authorId: AuthorId
}
type BookInfo = {
author: BookAuthor,
rating: BookRating
}
type BookWithInfo = Book & BookInfo
type RatingId = number
type RatingValue = number
type Rating = {
id: RatingId,
value: RatingValue
}
type Database = {
books: {[BookId]: Book},
authors: {[AuthorId]: Author},
ratings: {[RatingId]: Rating}
}
const database: Database = {
books: {
123: {
id: 123,
authorId: 345,
ratingId: 678,
title: 'Book Title'
}
},
authors: {
345: {
name: 'author name',
id: 345
}
},
ratings: {
678: {
id: 678,
value: 4.5
}
}
}
// Level 1
const fetchBook = (title: BookTitle) => Promise.resolve(Object.values(database.books).find(book => book.title === title))
const fetchAuthor = (id: AuthorId) => Promise.resolve(database.authors[id])
const fetchRating = (id: BookId) => Promise.resolve(database.ratings[id])
// Level 2
const getBook = (title: Promise<BookTitle>) => title.then(title => fetchBook(title))
const getAuthor = (book: Promise<Book>) => book.then(book => fetchAuthor(book.authorId))
const getRating = (book: Promise<Book>) => book.then(book => fetchRating(book.ratingId))
const assembleBookWithInfo = ([book, author, rating]: [Book, Author, Rating]): BookWithInfo => ({
...book,
author,
rating
})
// Level 3
const getBookWithInfo = (title): Promise<BookWithInfo> => {
const book = getBook(title)
const author = getAuthor(book)
const rating = getRating(book)
return Promise.all([ book, author, rating ])
.then(assembleBookWithInfo)
}
// Level 4
getBookWithInfo(Promise.resolve('Book Title'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment