Skip to content

Instantly share code, notes, and snippets.

@halfzebra
Last active December 28, 2018 12:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halfzebra/d8771245e185bcdd0b4008156aa960c7 to your computer and use it in GitHub Desktop.
Save halfzebra/d8771245e185bcdd0b4008156aa960c7 to your computer and use it in GitHub Desktop.
State Machine with Async Transitions
// Async Generator for implementing State Machines with asynchronous transitions.
//
// Try online: https://jsfiddle.net/ecf1bho9/
console.clear()
async function* state() {
let state = 0
let action
while (true) {
action = yield state
switch (action) {
case 'ADD':
state++
break
case 'SUB':
state--
break
case 'RESET':
state = 0
break
case 'FETCH':
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const data = await res.json()
state = data.length
break
}
}
}
const get = state()
get.next().then(({ value }) => value).then(console.log) // 0
get.next('FETCH').then(({ value }) => value).then(console.log) // 100
get.next('ADD').then(({ value }) => value).then(console.log) // 101
get.next('ADD').then(({ value }) => value).then(console.log) // 102
get.next('RESET').then(({ value }) => value).then(console.log) // 0
get.next().then(({ value }) => value).then(console.log); // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment