re: Explain JavaScript Promises like I am five. VIEW POST

FULL DISCUSSION
 

Think of a regular JS array as an envelope. You put one (or more) values into the envelope, and it gives you extra behaviour like map and reduce

const a = 1
      a.map(x => x * 2) // error
      a.reduce((x, y) => x + y, 0) // error

const wrapped = [a]
      wrapped.map(x => x*2) // [2]
      wrapped.reduce((x, y) => x + y, 1) // 3

In fact, we can say that JavaScript arrays are envelopes that have the special property of including multiple values.

Promises are similar. They are envelopes just like arrays are, but the special property they have is they handle future/potential/asynchronous values.

const f = x => new Promise((res, rej) => x ? res(x) : rej(x))

      f(2)
        .then(x => x * 2)
        .then(console.log) // 4

      f(null)
        .then(x => x * 2) // this function never runs
        .catch(x => console.error(`promise rejected for ${x}`)) // promise rejected for null

This is especially useful for managing asynchronous problems. By using a functional approach, Promise flows can be written in a top-down, left-to-right manner:

const handleAsText = response => response.text()
const unsafeDocumentWrite = text => {
  document.open();
  document.write(text);
  document.close();
}

fetch('google.com') // fetch API returns a Promise<Response>
  .then(handleAsText)
  .then(unsafeDocumentWrite)
 

I get it now...

In fact, we can say that JavaScript arrays are envelopes that have the special property of including multiple values.
Promises are similar. They are envelopes just like arrays are, but the special property they have is they handle future/potential/asynchronous values.

Thanks a lot!

 

Yup!

The non-eli5 answer is that Promises are (not 100% but basically) monads that encode asynchronous behaviour

code of conduct - report abuse