Dva: 怎样发出并发fetch/ajax且能够及时更新state?

Created on 27 Jun 2017  ·  7Comments  ·  Source: dvajs/dva

table中有一列数据需要通过ajax请求来更新,并且是有多少行就要发出多少个ajax请求,如果在effects里通过:

for (let i = 0; i < content.length; i++) {
   const status = yield call(service.status, id)
   content[i].status = status
   yield  put({type: 'updateState', payload: {content: content,}})
}

这样的方式来更新,请求会一条请求完请求下一条,效率不是很高。希望能够这些ajax能够并发的发出,即不通过yield停顿,同时又能及时更新state(一条请求成功就更新一次state), 不知哪位大神能指点一二?

table使用的是ant.design的。

Most helpful comment

  • 如果想等待全部结果都返回才做处理的话可以用all
*fetch(action, { call, all }) {
const [demands, orders, mediaorders] = yield all([
        call(fetch, {
          resource: 'stat/demands',
        }),
        call(fetch, {
          resource: 'stat/orders',
        }),
        call(fetch, {
          resource: 'stat/mediaorders',
        })
      ])
}
  • 如果想其中一个请求有返回结果就处理的话,可以用race
*fetch(action, { callWithLoading, put, race }) {
const [demands, orders, mediaorders] = yield race (...)

redux-saga可以看下saga的文档

All 7 comments

同问

1、yield 跟并发没有关系吧? 这样请求,应该就是并发的吧 (不确定)
2、为什么不合并为一次请求?

const results = yield [fun1(), fun2(), fun3()];

或者

function * fun(id) {}
const results = yield ids.map(fun);
const [demands, orders, mediaorders] = yield [
    call(fetch, {
        resource: 'stat/demands',
    }),
    call(fetch, {
        resource: 'stat/orders',
    }),
    call(fetch, {
        resource: 'stat/mediaorders',
    })
]

fetch可以返回Promise.all

@helloyou2012 可是这种写法虽然是并发了,但需要等到所有请求都完成后才能拿到结果,万一其中一个请求超时了,所有的数据都拿不到了。

  • 如果想等待全部结果都返回才做处理的话可以用all
*fetch(action, { call, all }) {
const [demands, orders, mediaorders] = yield all([
        call(fetch, {
          resource: 'stat/demands',
        }),
        call(fetch, {
          resource: 'stat/orders',
        }),
        call(fetch, {
          resource: 'stat/mediaorders',
        })
      ])
}
  • 如果想其中一个请求有返回结果就处理的话,可以用race
*fetch(action, { callWithLoading, put, race }) {
const [demands, orders, mediaorders] = yield race (...)

redux-saga可以看下saga的文档

用all做并发的话,如果有一个请求挂了,就会throw error,所有数据都会拿不到,要是想对正确的请求做后续处理呢

Was this page helpful?
0 / 5 - 0 ratings