我有一个遍历文件列表的函数,然后对于每个文件,它调用一个异步方法,该方法执行一些图像操作,然后将图像推送到数组。
问题是异步调用同时发生,因此它会锁定 UI。所以我想遍历列表,但只在前一个完成时调用该函数。
Array.from(files).forEach(data => {
if (data.size > 5000000) {
this.toastr_service.error('FILE ' + data.name + ' EXCEEDS FILE SIZE LIMIT (5MB)');
}else {
this.asyncFunc(data).subscribe(result => {
this._photos.push(result);
}, error => {
console.log(error);
});
}
});
使用map
数组的功能以及 RxJS 的功能forkJoin
forkJoin(Array
.from(files)
.map(file => file.size < 5000000 && this.asyncFunc(file) || undefined)
.filter(value => !!value)
).subscribe(([...responses]) => {
console.log(responses);
this._photos.push(...responses);
});
forkJoin
将进行所有文件大小低于 5Mb 的调用(map
并filter
处理好),一旦所有调用完成,响应将被推送到您的数组中。
编辑如果您希望对呼叫进行排序,请concat
改用:
concat(...Array
.from(files)
.map(file => file.size < 5000000 && this.asyncFunc(file) || undefined)
.filter(value => !!value)
).subscribe((...responses) => {
this._photos.push(...responses);
console.log(this.photos);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句