【问题标题】:How to upload images to firebase storage and wait for URLs to return before continuing如何将图像上传到 Firebase 存储并等待 URL 返回,然后再继续
【发布时间】:2021-04-28 07:21:58
【问题描述】:

我正在尝试创建一个“创建帖子”表单,用户可以在其中输入文本以及输入图像。

uploadImages() {
    const files = document.querySelector('#imagesInput').files;
    files.forEach(image => {
        console.log("uploading", image.name)
        const name = (+new Date()) + '-' + image.name;
        const task = fb.storage.child(name).put(image, {contentType: image.type});
        task.then(snapshot => {
            snapshot.ref.getDownloadURL().then(url => {
                console.log(url);
            })
        })
    });
}

图片上传过程需要首先发生,我需要在数据库中创建帖子之前返回所有 URL(作为一个数组)。

imageURLs = this.uploadImages(); // <-- Wait for this to complete and return the image URIs
this.createPost("Hello, world!", imageURLs) // <-- then do this

【问题讨论】:

    标签: javascript firebase-storage


    【解决方案1】:

    由于您调用异步getDownloadURL()方法的次数不定(即编码时未知),因此您需要使用Promise.all(),如下所示:

    uploadImages() {
        const files = document.querySelector('#imagesInput').files;
    
        const promises = [];
        files.forEach(image => {
            console.log("uploading", image.name)
            const name = (+new Date()) + '-' + image.name;
            const task = fb.storage.child(name).put(image, { contentType: image.type });
            promises.push(task);
        });
    
        return Promise.all(promises)
            .then(snapshotsArray => {
                // snapshotsArray is an array with a variable number of elements
                // You again need to use Promise.all
                const promises = [];
                snapshotsArray.forEach(snapshot => {
                    promises.push(snapshot.ref.getDownloadURL());
                })
                return Promise.all(promises);
            });
    }
    

    uploadImages()函数是异步的并返回一个Promise(因为Promise.all()then()返回Promises):因此你需要使用then()来调用它,如下:

    this.uploadImages()
    .then(imageURLs => {
       this.createPost("Hello, world!", imageURLs) 
    })
    

    【讨论】:

      【解决方案2】:

      .addOnSuccessListener 添加到您上传图片的行并在其中添加下一部分代码

      这样

      imageURLs = this.uploadImages().addOnSuccessListener(new OnSuccessListener() 
      ({
      
      this.createPost("Hello, world!", imageURLs)
      
      });
      

      我不确定代码是否完全正确,这取决于您到底想做什么,但它会让您大致了解您需要做什么

      【讨论】:

      • 您指出了我正确的方向,但是,第二个答案更详细。但是感谢您的帮助!
      • 别担心!乐意效劳 ! @阿里
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 2019-11-08
      • 2019-07-24
      • 1970-01-01
      • 2020-07-09
      • 2019-03-24
      • 2020-11-12
      相关资源
      最近更新 更多