异步任务跟不上for循环(firebase) [英] Async task could not keep up with for loop (firebase)

查看:53
本文介绍了异步任务跟不上for循环(firebase)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for (Uri mUri : mSelected) 
   {
       imagesRef = storageRef.child(postid + mUri.getLastPathSegment());
       imagesRef.putFile(mUri).addOnSuccessListener(task4 ->
       db.collection("posts").document(postid).update("photo_id", FieldValue.arrayUnion(imagesRef.getDownloadUrl())));
   }

因此,现在我正在使用Firestore和Firebase存储.我将(多个)图像上传到存储中,上传后,我获得了下载网址,并希望将其添加到我的Firestore中.因此,问题在于,只有最后一个图像被添加到firestore中,所有图像都被添加到存储中,而只有最后一个imgUrl被添加到firestore中.由于Firebase使用异步任务,我怀疑这是因为更新任务无法跟上循环.非常感谢任何帮助!!!

So, now i am working with firestore and firebase storage. I uploaded (multiple) images to the storage, and when it is uploaded, i get the download url and wants to add it into my firestore. So, the problem is, only the last image is added into firestore, all images are added into storage, but only the last imgUrl is added into firestore. Since firebase uses async tasks i suspect it is because the update task could not keep up with the loop. Any help is very much appreciated !!!

推荐答案

我认为问题可能出在 imagesRef 上,它是在之外声明的(Uri mUri:mSelected){...} ,因此在 addOnSuccessListener(...)响应之前将其替换.

I think the problem might be with imagesRef, it is declared outside of for (Uri mUri : mSelected) {...} and therefore it is being replaced before addOnSuccessListener(...) responds.

因此,对于(Uri mUri:mSelected){...} 在本地声明它,看看是否不能解决问题.像这样

So, declare it locally to for (Uri mUri : mSelected) {...} and see if it will not resolve the issue. Like this

for (Uri mUri : mSelected) 
{
       var imagesRef = storageRef.child(postid + mUri.getLastPathSegment());
       imagesRef.putFile(mUri).addOnSuccessListener(task4 ->
       db.collection("posts").document(postid).update("photo_id", FieldValue.arrayUnion(imagesRef.getDownloadUrl())));
 }

这篇关于异步任务跟不上for循环(firebase)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆