Code Talk #019: JavaScript Promises - Recap


Promises are a special kind of JavaScript object which allows for writing asynchronous programs. It can be in one of three states:

  • Pending
  • Resolved
  • Rejected


Once changed from an ending state, it can never be changed back. The data stored in a promise can be accessed via a .then() method upon resolution. Rejected promises issue a value via .catch(). ES6 provides keywords 'async' and 'await' which allow for writing syntactically concise promises.

### Event Loop


JavaScript is single-threaded, meaning that only one piece of code can execute at a time. Asynchronous code, therefore, does not mean multi-threaded. It simply means code execution happens out of order. During execution, when a promise (or any other asynchronous action such as setTimeout) is encountered, the provided callback is added to a separate queue. Meanwhile, the main thread will continue executing. Once complete, the first item in the queue is removed and executed until completion. This process repeats until the queue is empty.

Copied!