Skip to content

Commit

Permalink
Merge pull request #606 from mareksuscak/fix-failing-promises-example
Browse files Browse the repository at this point in the history
Fix failing Promises example from the documentation.
  • Loading branch information
goatslacker committed Jan 26, 2016
2 parents 1a04e9f + cd4da3a commit bff1f53
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 11 deletions.
16 changes: 9 additions & 7 deletions src/actions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,24 @@ export default function makeAction(alt, namespace, name, implementation, obj) {

// the action itself
const action = (...args) => {
const result = implementation.apply(obj, args)
const invocationResult = implementation.apply(obj, args)
let actionResult = invocationResult

// async functions that return promises should not be dispatched
if (result !== undefined && !isPromise(result)) {
if (fn.isFunction(result)) {
result(dispatch, alt)
if (invocationResult !== undefined && !isPromise(invocationResult)) {
if (fn.isFunction(invocationResult)) {
// inner function result should be returned as an action result
actionResult = invocationResult(dispatch, alt)
} else {
dispatch(result)
dispatch(invocationResult)
}
}

if (result === undefined) {
if (invocationResult === undefined) {
utils.warn('An action was called but nothing was dispatched')
}

return result
return actionResult
}
action.defer = (...args) => setTimeout(() => action.apply(null, args))
action.id = id
Expand Down
31 changes: 27 additions & 4 deletions test/async-action-test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Alt from '../'
import { assert } from 'chai'
import isPromise from 'is-promise'

const alt = new Alt()

Expand All @@ -8,6 +9,13 @@ const actions = alt.createActions(class AsyncActions {
fetch() {
return Promise.resolve('foo')
}

fetchAndDispatch() {
return (dispatch) => {
dispatch()
return Promise.resolve('foo')
}
}
})

const store = alt.createStore(class FooStore {
Expand All @@ -19,11 +27,26 @@ const store = alt.createStore(class FooStore {
onFetch() {
this.dispatched = true
}
onFetchAndDispatch() {
this.dispatched = true
}
})

export default {
'async actions'() {
actions.fetch()
assert(store.state.dispatched === false, 'async action is not automatically dispatched')
}
'async actions': {
afterEach() {
alt.recycle(store)
},

'are not dispatched automatically'() {
actions.fetch()
assert(store.state.dispatched === false, 'async action is not automatically dispatched')
},

'return the result of inner function invocation'() {
const promise = actions.fetchAndDispatch()
assert(isPromise(promise), 'async action does not return the result of inner function invocation')
assert(store.state.dispatched === true, 'async action is dispatched when the dispatch is invoked manually')
},
},
}

0 comments on commit bff1f53

Please sign in to comment.