在 vue Action 中,我想轮询我的后端(调用另一个 async
Action ,如下所述?)直到完成处理(前端显示加载程序直到进度结束)。
换句话说,我想重复进行 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 语句,或者什么才是最好的练习实现这一目标。
编辑:“非阻塞”,因为我最初是在 while
循环中使用 wait()
语句。这使得 UI 每次不得不等待时都会卡住。
最佳答案
我会使用递归函数来做到这一点。
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!
}
关于Vue.js 非阻塞 while 语句(轮询后端直到进度完成),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51819243/