Skip to content

Commit 6a0e430

Browse files
committed
implement onActionsResolved
1 parent 5d67ee5 commit 6a0e430

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

src/index.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ class Store {
2222
this._actions = Object.create(null)
2323
this._mutations = Object.create(null)
2424
this._subscribers = []
25+
this._pendingActions = []
2526

2627
// bind commit and dispatch to self
2728
const store = this
@@ -162,9 +163,19 @@ class Store {
162163
console.error(`[vuex] unknown action type: ${type}`)
163164
return
164165
}
165-
return entry.length > 1
166+
const res = entry.length > 1
166167
? Promise.all(entry.map(handler => handler(payload)))
167168
: entry[0](payload)
169+
const pending = this._pendingActions
170+
pending.push(res)
171+
return res.then(value => {
172+
pending.splice(pending.indexOf(res), 1)
173+
return value
174+
})
175+
}
176+
177+
onActionsResolved (cb) {
178+
Promise.all(this._pendingActions).then(cb)
168179
}
169180

170181
subscribe (fn) {

test/unit/test.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,45 @@ describe('Vuex', () => {
133133
})
134134
})
135135

136+
it('onActionsResolved', done => {
137+
const store = new Vuex.Store({
138+
state: {
139+
count: 0
140+
},
141+
mutations: {
142+
inc: state => state.count++
143+
},
144+
actions: {
145+
one ({ commit }) {
146+
return new Promise(r => {
147+
commit('inc')
148+
r(1)
149+
})
150+
},
151+
two ({ commit }) {
152+
return new Promise(r => {
153+
setTimeout(() => {
154+
commit('inc')
155+
r(2)
156+
}, 0)
157+
})
158+
}
159+
}
160+
})
161+
store.dispatch('one')
162+
store.dispatch('two')
163+
expect(store.state.count).to.equal(1)
164+
expect(store._pendingActions.length).to.equal(2)
165+
store.onActionsResolved(res => {
166+
expect(store._pendingActions.length).to.equal(0)
167+
expect(store.state.count).to.equal(2)
168+
expect(res.length).to.equal(2)
169+
expect(res[0]).to.equal(1)
170+
expect(res[1]).to.equal(2)
171+
done()
172+
})
173+
})
174+
136175
it('getters', () => {
137176
const store = new Vuex.Store({
138177
state: {

0 commit comments

Comments
 (0)