Finite State Machines and JS

  1. Every async function’s state diagram starts with three states: State 0, Resolved, and Rejected. <Edit> S̶i̶n̶c̶e̶ ̶P̶r̶o̶m̶i̶s̶e̶s̶ ̶r̶u̶n̶ ̶i̶n̶ ̶a̶ ̶m̶i̶c̶r̶o̶t̶a̶s̶k̶ ̶t̶h̶e̶r̶e̶ ̶i̶s̶ ̶a̶ ̶l̶i̶t̶t̶l̶e̶ ̶b̶i̶t̶ ̶o̶f̶ ̶t̶i̶m̶e̶ ̶b̶e̶t̶w̶e̶e̶n̶ ̶t̶h̶e̶ ̶a̶s̶y̶n̶c̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶b̶e̶i̶n̶g̶ ̶c̶a̶l̶l̶e̶d̶ ̶(̶c̶r̶e̶a̶t̶i̶n̶g̶ ̶t̶h̶e̶ ̶p̶r̶o̶m̶i̶s̶e̶)̶ ̶a̶n̶d̶ ̶t̶h̶e̶ ̶s̶t̶a̶r̶t̶ ̶o̶f̶ ̶i̶t̶’̶s̶ ̶c̶o̶d̶e̶ ̶r̶u̶n̶n̶i̶n̶g̶.̶ (Promises actually run eagerly, so there is no state 0. I misunderstood the difference between methods registered with then which are always called asyncronously using microtasks and the promise code itself. I apologize.)</Edit> The Resolved and Rejected states come from the function returning a Promise but in some async functions they might not be reachable (as is the case for the Rejected state in the example above).
  2. Find the rest of the states by looking for the await keyword. “An await is a state.” In most cases they will be on their own line to avoid confusion like this:
  3. Next find the transitions by looking at all the code between those awaits. This linear example is pretty easy — the transitions are the lines before, between, and after the await lines, but if you have loops with breaks, continues, and named loops… it can be more difficult to keep track of what states can transition to which other states.
  4. Lastly, circle all the states that aren’t Resolved and Rejected and call that Pending. From the outside world, we can only see the original Promise states. The callbacks we register are only called when the async function transitions to Resolved or Rejected.




I write a lot of ECMAScript… enough to have plenty of mistakes to learn from.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Setting Up Monorepo With Create React App

Learn React and Redux with a Project (2021)

Intro to Webpack

Did Someone say Composition?

8 Tips for an Agile Debugging of a Web Application

Laravel Redirect::to() vs. Redirect::away()

Google Maps in Angular with Marker, Info Window and Marker Clustering.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Evan Brass

Evan Brass

I write a lot of ECMAScript… enough to have plenty of mistakes to learn from.

More from Medium

Exploring more about reducers, pure functions,side-effects ,useEffect() ,async calls and context..!

A Beginner’s quick setup of a basic JavaScript project, and linking a Jest Test file.

Package.json file where we have updated Jest:test

A good case for Eval in JavaScript

Masking Uploaded File Name