我正在使用firebase存储桶保存文件,并将它们的下载链接保存到数据库中。
除了在我执行foreach循环(_lodash)后文件索引被混淆之外,一切都应该正常工作。
getFiles(e){
this.outPutFiles = e;
_.each(this.outPutFiles, ((file) => {
const ref = this._storage.ref(file);
return ref.getDownloadURL().subscribe(url => this.img_array.push(url));
}));
}预期行为应为:
this.outPutFiles = [
0:"o-t-status-files/.....Qd5bGm"
1:"o-t-status-files/.....dz2bd8"
]和
this.img_array = [
0:"https://firebase....%2FJ6Qx9........Qd5bGm"
1:"https://firebase....%2FJ6Qx9........dz2bd8"
]不幸的是,有时this.img_array中的文件索引与this.outPutFiles变量上的索引中的文件不匹配。
例如,this.img_array可能会变成这样...
this.img_array = [
0:"https://firebase....%2FJ6Qx9........dz2bd8"
1:"https://firebase....%2FJ6Qx9........Qd5bGm"
]索引0处的文件已移至索引1,索引1处的文件已移至索引0。
如何防止出现这种情况,以确保this.outPutFiles和this.img_array数组中的文件索引都匹配?
发布于 2018-08-24 01:20:31
原因ref.getDownloadURL()是异步的,因此outPutFiles[1].getDownloadURL()可能会完成之前的outPutFiles[0].getDownloadURL()。
尝试如下操作(或使用rxjs操作符):
Promise.all(_.map(this.outPutFiles, file => this._storage.ref(file).getDownloadURL()))
.then(img_array => console.log(img_array))https://stackoverflow.com/questions/51990598
复制相似问题