函数多次运行Javascript

问题描述

我是新来的本地人,我正在尝试上传在Firebase中拍摄的照片。所有这些工作正常,那么我想将下载URL保存在firebase数据库中。这也仅在我上传照片时有效,他将代码2x上传到firebase数据库。我发现这可能是由于异步功能引起的。但是如果我忽略了等待,refImage.getDownloadURL ();将不再起作用。有没有人可以帮助我,使他只将数据上传到数据库一次?以下是我目前的职位。预先谢谢你!

当我从以下位置调用this.setProfileImage()时

firebase
      .storage ()
      .ref (`images / profilepictures / $ {filename}`)
      .putFile (this.state.imageUri)
      .on (
        firebase.storage.TaskEvent.STATE_CHANGED,snapshot => {
          let state = {};
          state = {
            ... state,progress: (snapshot.bytesTransferred / snapshot.totalBytes) * 100 // Calculate progress percentage
          };
          if (snapshot.state === firebase.storage.TaskState.SUCCESS) {
            const allImages = this.state.images;
            allImages.push (snapshot.downloadURL);
            state = {
              ... state,uploading: false,imgSource: '',imageUri: '',progress: 0,images: allImages
            };
            AsyncStorage.setItem ('images',JSON.stringify (allImages));
           
             //this.loadProfileImage ();
          }
          this.setState (state);
          this.addToDB ('images / profilepictures /' + filename);
        },error => {
          unsubscribe ();
          alert ('Sorry,Try again.');
        }
      );



  uploadData(){
    
    firebase.database().ref('messages/0/posts').push({
      date: '18-09-2020',function: 'Leidsters',image: this.downloadUrlNew,name: 'Juffen',post: 4,text: "Dit is een test 4",type: true
      
  }).then((data)=>{
      //success callback
      console.log('data ',data)
  }).catch((error)=>{
      //error callback
      console.log('error ',error)
  })
 

}

addToDB(url){ 

  this.setProfileImage(url);

}

async setProfileImage(imageUrl){
  var refImage = firebase.storage().ref(imageUrl);
  this.downloadUrlNew = await refImage.getDownloadURL();
  this.uploadData();
  /*this.setState({
    downloadUrlNew: await refImage.getDownloadURL(),})*/
    
}

他将具有相同值的2x字段相加:

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)