Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Promises are _Fun_damental

Promises are _Fun_damental

A JavaScript promise is a handy container for a value you expect to get later. But a promise is also a value itself, and you can do some useful stuff just knowing you have a promise.

As given at the 2018-07-18 Columbus Javascript user group meeting (plus a couple of typo fixes).

Neal Lindsay

July 18, 2018
Tweet

More Decks by Neal Lindsay

Other Decks in Programming

Transcript

  1. fetch('/url') // promise "a" .then(r => r.json() // promise "d"

    (maybe) ) // promise "b" .then(v => console.log(v)) // promise "c"
  2. const myFunc = (x) => x + 1 const twice

    = (f) => (x) => f(f(x)) console.log( twice(myFunc)(0) )
  3. • handler functions • higher-order handler functions • async functions

    • higher-order async functions • aggregation
  4. const log = (v) => { console.log(v) return v }

    const errLog = (e) => { console.error(e) throw e }
  5. const logWith = (m) => (v) => { console.log(m, v)

    return value } const errLogWith = (m) => (e) => { console.error(m, e) throw e }
  6. const recoverWith = (v) => () => v fetch('/url') .then(r

    => r.json()) .catch(recoverWith({val: 1})) .then(doWhatever)
  7. // always rejects after ms const timeoutAfter = async (ms)

    => new Promise((_, reject) => { setTimeout(() => { reject(Error( `Timed out after ${ms}` )) }, ms) })
  8. // too big to show in a slide const c

    = cancelable() c(fetch(url)) .then(r => c(r.json())) .then(doSomething) c.cancel('never mind')
  9. const modalQuery = async (q) => {...} Promise .all([ modalQuery('accept

    privacy policy?'), modalQuery('accept code of conduct?') ]) .then(createAccount)
  10. const lockify = (f) => { let lock = Promise.resolve()

    return async (...params) => { const result = lock .then(() => f.apply(undefined, params)) lock = result.catch(() => 1) return result } }
  11. const promiseCache = async (f, options) => { // way

    too much stuff for a slide! } const cachedFetch = promiseCache(fetch) cachedFetch('url').then(something) cachedFetch('url').then(somethingElse)
  12. const hang = () => new Promise() const firstGood =

    (ps) => { return Promise.race( ps.map(p => p.catch(hang)) ) }
  13. const hang = () => new Promise() const firstGood =

    (ps) => { return Promise.race( ps.map(p => p.catch(hang)) ) } // if they all fail...
  14. const firstGood = async (ps) => { return new Promise((resolve,

    reject) => { ps.forEach(p => p.then(resolve)) Promise.all(ps) .catch(e => Promise .all(ps.map(p => p.catch(() => 0))) .then(() => reject(e)) ) }) } //