Sfoglia il codice sorgente

implement onActionsResolved

Evan You 8 anni fa
parent
commit
6a0e430061
2 ha cambiato i file con 51 aggiunte e 1 eliminazioni
  1. 12 1
      src/index.js
  2. 39 0
      test/unit/test.js

+ 12 - 1
src/index.js

@@ -22,6 +22,7 @@ class Store {
     this._actions = Object.create(null)
     this._actions = Object.create(null)
     this._mutations = Object.create(null)
     this._mutations = Object.create(null)
     this._subscribers = []
     this._subscribers = []
+    this._pendingActions = []
 
 
     // bind commit and dispatch to self
     // bind commit and dispatch to self
     const store = this
     const store = this
@@ -162,9 +163,19 @@ class Store {
       console.error(`[vuex] unknown action type: ${type}`)
       console.error(`[vuex] unknown action type: ${type}`)
       return
       return
     }
     }
-    return entry.length > 1
+    const res = entry.length > 1
       ? Promise.all(entry.map(handler => handler(payload)))
       ? Promise.all(entry.map(handler => handler(payload)))
       : entry[0](payload)
       : entry[0](payload)
+    const pending = this._pendingActions
+    pending.push(res)
+    return res.then(value => {
+      pending.splice(pending.indexOf(res), 1)
+      return value
+    })
+  }
+
+  onActionsResolved (cb) {
+    Promise.all(this._pendingActions).then(cb)
   }
   }
 
 
   subscribe (fn) {
   subscribe (fn) {

+ 39 - 0
test/unit/test.js

@@ -133,6 +133,45 @@ describe('Vuex', () => {
       })
       })
   })
   })
 
 
+  it('onActionsResolved', done => {
+    const store = new Vuex.Store({
+      state: {
+        count: 0
+      },
+      mutations: {
+        inc: state => state.count++
+      },
+      actions: {
+        one ({ commit }) {
+          return new Promise(r => {
+            commit('inc')
+            r(1)
+          })
+        },
+        two ({ commit }) {
+          return new Promise(r => {
+            setTimeout(() => {
+              commit('inc')
+              r(2)
+            }, 0)
+          })
+        }
+      }
+    })
+    store.dispatch('one')
+    store.dispatch('two')
+    expect(store.state.count).to.equal(1)
+    expect(store._pendingActions.length).to.equal(2)
+    store.onActionsResolved(res => {
+      expect(store._pendingActions.length).to.equal(0)
+      expect(store.state.count).to.equal(2)
+      expect(res.length).to.equal(2)
+      expect(res[0]).to.equal(1)
+      expect(res[1]).to.equal(2)
+      done()
+    })
+  })
+
   it('getters', () => {
   it('getters', () => {
     const store = new Vuex.Store({
     const store = new Vuex.Store({
       state: {
       state: {