Skip to content

Instantly share code, notes, and snippets.

@topliceanu
Last active August 29, 2015 13:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topliceanu/9955397 to your computer and use it in GitHub Desktop.
Save topliceanu/9955397 to your computer and use it in GitHub Desktop.
A implementation of the _.any api but for asynchronous computation and Q promises.
assert = (require 'chai').assert
Q = require 'q'
util = require './util'
describe '.any()', ->
it 'should fail when no promise resolves', (done) ->
fns = [
-> Q.reject new Error 'some error'
-> throw new Error 'some nasty error'
]
(util.any fns).then ->
assert.ok false, 'should not get here at all'
, (error) ->
assert.ok true, 'should fail because none of the fns resolves'
.then (-> done()), done
it 'should succeed when at least one function resolves', (done) ->
test = 0
fns = [
-> Q.reject new Error 'some error'
-> Q()
-> throw new Error 'some nasty error'
-> test = 1; throw new Error 'some very nasty errors'
]
(util.any fns).then ->
assert.ok true, 'should succeed because one fns succeeded'
assert.equal test, 0, 'the next functions after the '+
'successfull one will not be executed'
.then (-> done()), done
_ = require 'underscore'
Q = require 'q'
exports.any = any = (functions) ->
###
Method executes async functions one by one.
It will stop in either of these cases:
- on the first function in the chain that resolves successfully.
- when the chain is completed and all function reject the promise.
NOTE This method is similar to _.any but only for async computation.
TODO This is hackish. Find a better way to resolve this.
@param {Array<Function>} list of functions returning Q.Promise
@return {Object} Q.Promise which resolves to true if at least one of
the functions resolves or false otherwise.
###
_.reduce functions, (continuation, fn) ->
continuation.then ->
Q()
, (error) ->
return fn()
, Q.reject new Error 'START'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment