[英]Listr: Observable on array map
I want to download a group o files and reporting the progress using Listr and RxJs but when i run it loops and display incorrect index of the array. 我想下载一个o组文件并使用Listr和RxJs报告进度,但是当我运行它时会循环并显示错误的数组索引。
That's the code of the task [source code] : 这就是任务的代码[源代码] :
{
title: 'Downloading...',
task: (ctx) => rx.Observable.create((observer) => {
const count = ctx.photos.length;
const urls = ctx.photos.map((photo) => photo.urls.raw)
urls.forEach(async (url, index) => {
let data = await download(url);
if ( index !== count - 1 ) {
observer.next(index);
} else {
observer.complete()
}
})
})
}
That's the result (is not the exact same function, but the problem is the same) 这就是结果(功能不完全相同,但问题是相同的)
.forEach
will run synchronously even though the callback to it is using async
/ await
. 即使
.forEach
的回调使用async
/ await
,它也将同步运行。 To be honest I think this is a better approach since it allows multiple downloads to happen at once and you don't have to depend on the order of the downloads. 老实说,我认为这是一种更好的方法,因为它允许一次进行多次下载,而您不必依赖下载的顺序。 If you want this to display in order you can just maintain your own counter:
如果您希望以此顺序显示,则只需维护自己的计数器即可:
let downloadedCount = 0;
urls.forEach(async (url, index) => {
let data = await download(url);
if ( index !== count - 1 ) {
observer.next(++downloadedCount);
} else {
observer.complete()
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.