Asynchronous Code & Promises

Node.js is a cross-platform runtime environment and a library for running Javascript applications outside of the browser.  It uses non-blocking I/O and asynchronous events to create a highly performance environment built on Google’s V8 engine.

The engine is consisted of the memory heap (where memory allocations happen) and the call stack (where the stack frames are as code executes).

Asynchronous callbacks–allow us to execute heavy code without blocking the UI and making the browser unresponsive.

You can execute any chunk of code asynchronously by using setTimeout(callback, milliseconds).  setTimeout doesn’t automatically put your callback on the event loop queue.  It sets up a timer, and when that timer expires, your callback will enter the event loop to be executed.

The event loop is a special queue for asynchronous callbacks.  Its job is to monitor the call stack and the callback queue.  If the call stack is empty, it will take the first event from the callback queue and push it to the call stack, which effectively runs it.

Below is an awesome gif showing this process of queueing up asynchronous callbacks and executing them.

asyncPromises are the solution to callback hell.

  • It is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s rejected.
  • A promise may be in one of the 3 possible states: fulfilled, rejected, or pending.
  • All promise instances get a then method which allows you to react to the promise.  then method callbacks  can also be chained.
  • The catch callback is executed when the promise is rejected.

Screen Shot 2018-01-01 at 8.09.19 PM

Sources:

Advertisements
Asynchronous Code & Promises

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s