Skip to content

Instantly share code, notes, and snippets.

@NicholasBoll
Last active February 5, 2018 14:27
Show Gist options
  • Save NicholasBoll/805b9ef46c5f2acc921ee9250bb434ed to your computer and use it in GitHub Desktop.
Save NicholasBoll/805b9ef46c5f2acc921ee9250bb434ed to your computer and use it in GitHub Desktop.
Example of a promise chain
interface Todo {
id: string
name: string
done: boolean
}
const createTodo = (name: string) => new Promise<Todo>((resolve) => {
setTimeout(
resolve,
100,
{ id: String(Math.round(Math.random() * 1000)), name, done: false }
)
})
// could return a new promise for force this to be always synchronous
const markAsDone = (todo: Todo): Todo => ({...todo, done: true })
const updateName = (name: string) => (todo: Todo) =>
new Promise<Todo>(resolve => {
setTimeout(resolve, 100, {...todo, name })
})
const saveTodo = (todo: Todo) => new Promise<Todo>((resolve) => {
setTimeout(resolve, 100, todo)
})
createTodo('Learn Cypress command API')
.then(saveTodo)
.then(updateName('Learn Cypress composition'))
.then(markAsDone)
.then(saveTodo)
.then(console.log)
// a few hundred milliseconds later:
// {id: "200", name: "Learn Cypress composition", done: true}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment