Skip to content

Instantly share code, notes, and snippets.

@amouratoglou
Last active February 8, 2020 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amouratoglou/34f33bbd26e55af22b12050d5c53ff76 to your computer and use it in GitHub Desktop.
Save amouratoglou/34f33bbd26e55af22b12050d5c53ff76 to your computer and use it in GitHub Desktop.
Javascript Promises and Async Programming

Introduction

This document has notes related with Javascript Promises and Async Programming

Promises in Javascript

  • Async Programming
  • Consuming and creating promises
  • Async Await

What problem they solve?

To avoid undefined responses when dealign with external API content retrieved via AJAX calls, we can use Promises as a technique that allow us to ensure we have the data before we try to use it. Callback pyramid of Doom, many levels of nesting indentation of functions, a.k.a. "Callback hell".

  • The "bad" part is that the code becomes dirty and is error prone.
  • Error handling , the pyramid of doom can make the code even messier, adding more indentation.
  • Hard to read

Promises allow us to execute code without massive nesting callbacks.

Promises definition according to Mozilla MDN: Object that represents the eventual completion (or failure) of an async operation, and its value.

Promises have 3 states:

  1. Pending state -> while the promise is happening is pending, until it is...
  2. Fullfied state -> returns a single value grabbed from for example an API.
  3. Rejected state -> the promise fails so it returns a reason why it was rejected similar to a Catch function in a try catch block.
  • Other terms: Setteld and Resolved, both refer to the same state - either Fullfied or Rejected state, it is no longer pending.

Promises in "real life"

We can get data from an API, to see how this works in real life.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment