Skip to content

Instantly share code, notes, and snippets.

@wires
Last active January 21, 2017 21:20
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 wires/0ff0cdcae99e90f5a17842afcb2c5a12 to your computer and use it in GitHub Desktop.
Save wires/0ff0cdcae99e90f5a17842afcb2c5a12 to your computer and use it in GitHub Desktop.
twittable-promise

Promise library in 137 chars

Execute in series and wait for result

// [() -> P a, a -> P b, ..., y -> P z] -> P z
P.ser([ ... ])

Execute in parallel and wait for result

// [() -> P (), ...] -> P ()
P.par([ ... ])
const P = require('./P.js')
const delay = ms => new Promise(ok => setTimeout(ok, ms))
const log = x => () => console.log(x)
P.ser([
() => delay(2000).then(log('1')),
() => delay(1500).then(log('2')),
() => delay(1000).then(log('3'))
])
.then(() => P.par([
() => delay(2000).then(log('3')),
() => delay(1500).then(log('2')),
() => delay(1000).then(log('1'))
]))
.then(() => console.log('done'))
e=exports
e.ser=x=>x.reduce((p,q)=>p?p.then(z=>q(z)):q(),0)
e.par=x=>new Promise((k,r)=>{N=x.length;x.map(p=>p().then(_=>--N?_:k(),r))})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment