Last active
February 5, 2018 14:27
-
-
Save NicholasBoll/805b9ef46c5f2acc921ee9250bb434ed to your computer and use it in GitHub Desktop.
Example of a promise chain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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