在vue动作中,我想轮询后端(调用另一个async
动作,如下所述?),直到某些事情完成处理为止(前端显示一个加载程序,直到进度结束为止)。
换句话说,我想重复进行如下所示的API调用:
actions: {
load: async ({dispatch, commit, state}, {args}) => {
await dispatch('progressPolling', {progressUrl, userId})
// continue ONLY when progress has finished, else blocks at this statement
...
}
progressPolling: async ({dispatch, commit}, {progressUrl, userId}) => {
var finished = false
while(!finished) : {
var progress = await dispatch('getResource', {url: progressUrl, userId: userId})
finished = (progress.data.finished === true)
// timeout of 2 secs
}
}
...
}
我的理解是,您可以使用setTimeout()
语句在两次调用之间等待,但是不确定如何将其转换为无阻塞的while语句,或者仅是实现此目的的最佳实践。
EDIT :“非阻塞”,因为我最初是在wait()
循环中使用while
语句。这使得UI每次必须等待时都冻结。
答案 0 :(得分:1)
我将使用递归函数来做到这一点。
progressPolling: async ({dispatch, commit}, {progressUrl, userId}) => {
// Define a recursive function
async function getResource (resolve) {
const progress = await dispatch('getResource', {url: progressUrl, userId: userId})
// Recurse when not finished
if (progress.data.finished !== true) {
setTimeout( () => getResource(resolve), 2000);
}
}
// Kick the recursive function
return new Promise (resolve => getResource(resolve))
// Finished!
}