我正在开发一个必须管理大量数据的应用程序.
在init进程中,必须在用户看到加载栏时进行几次api调用.
这是我的初始化动作:
export function init(key) {
return (dispatch, getState) => {
// start init
dispatch(initStart());
setTimeout(() => {
dispatch(initProcess(10));
}, 0)
return Promise.all([
// load users
dispatch(loadUsers(key)).then(() => {
dispatch(initProcess(30));
}),
// load other stuff
// ...
// load articles
dispatch(loadArticles(key)).then(() => {
dispatch(initProcess(60));
}),
// should be executed after all actions/reducers are done
]).then(() => {
setTimeout(() => {
dispatch(initFinish());
}, 700);
});
}
}
到目前为止它完美无缺,但会有20k到50k的文章.后端必须执行一些连接才能将数据放在一起,所以我确信如果我尝试将它们整合在一起,我将得到服务器超时.
我们的想法是首先获取总数,然后循环获取1k个文章.但它不会像我需要的那样工作.我会在文章被计数后发送initFinish,但在获取之后不会发送.
这是loadArticles动作:
export function loadArticles(key) {
return (dispatch, getState) => {
// check local db first
// get total number
return dispatch(countArticles(key))
.then(result => {
Promise.all([
// No idea how to put the loop in here :(
dispatch(fetchArticles(key, 1000)),
])
});
}
}
我还没有循环,但那不是重点.逻辑保持不变.我在fetchArticles完成之前返回dispatch(countArticles(key)).
有人提示吗?那将是真棒.
编辑
coutArticles和fetchArticles
function countArticles(key) {
return {
[CALL_API]: {
types: [ COUNT_ARTICLES_REQUEST, COUNT_ARTICLES_SUCCESS, COUNT_ARTICLES_FAILURE ],
endpoint: `articles`,
schema: Schemas.ARTICLE_COUNTER
}
}
}
function fetchArticles(key, take, skip) {
return {
[CALL_API]: {
types: [ FETCH_ARTICLES_REQUEST, FETCH_ARTICLES_SUCCESS, FETCH_ARTICLES_FAILURE ],
endpoint: `articles/${take}/${skip}`,
schema: Schemas.ARTICLE_ARRAY
}
}
}
中间件与es here相同
2.编辑
如果我改变
// get total number
return dispatch(countArticles(key))
.then(result => {
Promise.all([
// No idea how to put the loop in here :(
dispatch(fetchArticles(key, 1000)),
])
});
至
// get total number
dispatch(countArticles(key))
.then(result => {
return Promise.all([
// No idea how to put the loop in here :(
dispatch(fetchArticles(key, 1000)),
])
});
我得到Uncaught TypeError:无法在dispatch(loadArticles(key))上读取未定义的属性’then’.
3.编辑
几天后我还在打^^
这是简化的init函数,它应该(仅)获取计数结果,然后获取文章:
但是现在我已经失败了:
export function init(key) {
return (dispatch, getState) => {
countArticles(key).then(result => {
console.log(result);
});
}
}
输出:
Uncaught TypeError: countArticles(...).then is not a function
最佳答案 我也有链接派遣的问题;它应该返回一个承诺,但我无法让它工作.
所以我会以这种方式改变逻辑
countArticles(key).then(result => {
dispatch( {
type: RECEIVED_NUM_ARTICLES,
value: result
})
Promise.all([...Array(Math.floor(result/1000))].map(_ =>
fetchArticles(key,1000).then(res => dispatch( {
type: RECEIVED_1000_ARTICLES,
value: res
})
)).then( _ => dispatch({
type: RECEIVED_EVERYTHING
value: 'whatever'
})
)
)
(我没有测试这段代码)
但基本上:fetch然后调度结果,然后链接另一个fetch / dispatch序列等…
循环需要返工才能获取模数
这种方法的优点是,您可以在拥有文章时使用文章数更新UI,然后提取每1000篇文章的更新,最后在完成后通知